2017-08-05 222 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