gpt4 book ai didi

android - 从其他线程更改 View

转载 作者:行者123 更新时间:2023-11-29 18:11:55 28 4
gpt4 key购买 nike

我写了一段代码来从互联网上下载一张图片。我必须在动态创建的 ImageView 中显示它。

而且我得到一个错误,只有创建 View 层次结构的原始线程才能触及它的 View 。我知道我必须写一个句柄,但我该怎么做?

这是我的代码:

public class ResimCek implements Runnable {

int resimID = 0;

public ResimCek(int parcaID) {
// store parameter for later user
resimID = parcaID;
}

public void run() {

int resID = getResources().getIdentifier(Integer.toString(resimID) , "tag", getPackageName());
ImageView resim = (ImageView) findViewById(resID);

Drawable image = ImageOperations(getBaseContext(),"http://141.11.11.206/parca/" + Integer.toString(resimID) + ".jpg" ,"I" + Integer.toString(resimID) + ".jpg");

// I AM GETTING ERROR HERE ******************
resim.setImageDrawable(image); // *************************
}
}

private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(new URL(url).openConnection().getInputStream(),saveFilename);
return d;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

public Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
private void MalzemeEkle(String malzemeKodu, String malzemeTanimi) {
ImageView parcaresmi = new ImageView(this);
parcaresmi.setId(Integer.parseInt(malzemeKodu));
Runnable r = new ResimCek(Integer.parseInt(malzemeKodu));
new Thread(r).start();
}

最佳答案

public class ResimCek implements Runnable {

int resimID = 0;

public ResimCek(int parcaID) {
// store parameter for later user
resimID = parcaID;
}

public void run() {

int resID = getResources().getIdentifier(Integer.toString(resimID) , "tag", getPackageName());
ImageView resim = (ImageView) findViewById(resID);

Drawable image = ImageOperations(getBaseContext(),"http://141.11.11.206/parca/" + Integer.toString(resimID) + ".jpg" ,"I" + Integer.toString(resimID) + ".jpg");

// I AM GETTING ERROR HERE ******************
resim.setImageDrawable(image); // *************************
}
}



new Handler().post(new ResimCek(Integer.parseInt(malzemeKodu))); instead of new Thread(r).start();

无论如何,如果这是一个 Activity.. 那么

runOnUIThread(new ResimCek(Integer.parseInt(malzemeKodu))); `instead of new Thread(r).start();` 

也会工作..

关于android - 从其他线程更改 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10209819/

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