2017-08-05 223 views
0

我需要用線程運行我的代碼的一些部分。但是我訪問run()函數中的變量時遇到問題。變量(也是函數參數)需要被定義爲final,但是當我這樣做時,我不能在run()函數中更改它們的值。例如,現在變量ivrun()方法中不可訪問。在類函數中運行線程

有什麼辦法可以解決這個問題嗎?

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 

    LayoutInflater inflater = getLayoutInflater(); 

    convertView = getLayoutInflater().inflate(R.layout.gallery_gridsq, parent, false); 
    ImageView iv = (ImageView) convertView.findViewById(R.id.icon); 
    final File file = new File(Uri.parse(getItem(position).toString()).getPath()); 


    Runnable runnable = new Runnable() { 
     @Override 
     public void run() { 
      Bitmap bmp = null; 
      BitmapFactory.Options options = new BitmapFactory.Options(); 
      options.inJustDecodeBounds = true; 
      try { 
       BitmapFactory.decodeStream(new FileInputStream(file), null, options); 
      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } 

      options.inJustDecodeBounds = false; 
      options.inSampleSize = 2; 
      try { 
       bmp = BitmapFactory.decodeStream(new FileInputStream(file), null, options); 
      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } 

      iv.setImageBitmap(bmp); 
     } 
    }; 

    new Thread(runnable).start(); 
    return convertView; 
} 
+0

你不重新分配'iv'變量......它可以是'final' –

回答

0

你需要在這裏做的是讓iv決賽:

final ImageView iv = (ImageView) convertView.findViewById(R.id.icon); 

在此背景下final意味着你不能改變對象的引用iv點,但你仍然可以調用任何方法的。另外要小心爲每個視圖創建新的Thread,我建議使用由ExecutorService代表的線程池。

+0

我已經完成了!但現在只有一個圖像視圖,裏面沒有圖像:( – sara

+0

@sara檢查代碼/ logcat,也許你有一些錯誤;你也解碼相同的流兩次。 – nikis