开发者

ImageView doesn't change image after download

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


Because you should set your Drawable in UI thread. Like this

        new Thread() {
        @Override
        public void run() {
            try {
                final Drawable drawable = LoadImageFromWebOperations("http://www.androidpeople.com/wp-content/uploads/2010/03/android.png");
                imgView.post(new Runnable(){
                    imgView.setImageDrawable(drawable);
                });
            } catch (Exception e) {
                Log.e("TAG","" + e);
            }
        }
    }.start();


I use Prime for all of my image loading, it will make actions like this super easy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜