gpt4 book ai didi

java - 使用线程时 ImageView 不显示图像

转载 作者:行者123 更新时间:2023-12-02 12:25:19 25 4
gpt4 key购买 nike

我使用此代码来显示图像,因为我在没有线程的情况下运行它它工作正常,但使用线程我只是获得 ImageView ,其中没有任何图片。对我来说,在程序的这一部分使用线程很重要,因为它非常慢:(这是我的代码:

        @Override
public View getView(final int position, View convertView, ViewGroup parent) {
Log.e("sara" , "this part takes time");


LayoutInflater inflater = getLayoutInflater();

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

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;
}
}

最佳答案

使用AsyncTask

文档:https://developer.android.com/reference/android/os/AsyncTask.html

AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

doInBackground()中执行繁重的操作,并在onPostExecute()中将图像设置为imageView。

关于java - 使用线程时 ImageView 不显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45528701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com