下载后 ImageView 不会更改图像
我是开发 Android 应用程序的初学者。我正在尝试从 URL 加载图像到使用线程的ImageView
。我的想法是我想在不中断整个过程的情况下加载图像。
问题是 ImageView
在下载完成后不加载图像;我必须单击主页按钮才能使 ImageView 加载图像。
我的代码有错误吗?
public class imageActivity extends Activity {
private ImageView imgView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imgView =(ImageView)findViewById(R.id.img);
new Thread() {
@Override
public void run() {
try {
Drawable drawable = LoadImageFromWebOperations("http://www.androidpeople.com/wp-content/uploads/2010/03/android.png");
imgView.setImageDrawable(drawable);
} catch (Exception e) {
Log.e("TAG","" + e);
}
}
}.start();
}
private Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
System.out.println("Exc=" + e);
return null;
}
}
}
I am a beginner in developing Android applications. I am trying to load an image from an URL to an ImageView
using a thread. The idea is I want to load the image without interrupting overall process.
The problem is the ImageView
doesn't load the image after it has finished downloading it; I must click the home button to make ImageView
load the image.
Is there a mistake in my code?
public class imageActivity extends Activity {
private ImageView imgView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imgView =(ImageView)findViewById(R.id.img);
new Thread() {
@Override
public void run() {
try {
Drawable drawable = LoadImageFromWebOperations("http://www.androidpeople.com/wp-content/uploads/2010/03/android.png");
imgView.setImageDrawable(drawable);
} catch (Exception e) {
Log.e("TAG","" + e);
}
}
}.start();
}
private Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
System.out.println("Exc=" + e);
return null;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为你应该在 UI 线程中设置你的 Drawable 。像这样
Because you should set your Drawable in UI thread. Like this
我使用 Prime 来加载所有图像,它将使这样的操作变得超级简单。
I use Prime for all of my image loading, it will make actions like this super easy.