在一个View内使用runOnUiThread

20

我正在制作一个自定义的 ImageView,其中一个方法是从URL加载图像。 我想在线程中检索位图并在UI线程中加载位图。

如何使用 runOnUIThread() 调用绘制位图?

是否有某种内置函数?或者我应该在构造函数中创建一个 Handler 并将其用于在UI线程中运行可运行项?


2
使用Handler。如果我没记错,runOnUIThread是Activity的一个方法。 - Rich
3个回答

55

通过AsyncTask下载图像,然后在其onPostExecute方法中设置到你的视图中

或者

从一个单独的图像下载线程中使用Viewpost方法,它将始终在UI线程上运行其Runnable

yourImageView.post(new Runnable() {
    @Override
    public void run() {
        // set the downloaded image here

    }
});

请务必阅读Cyrilchampier在评论中发布的链接。谢谢。 - John Pang

7
你可以像这样做:

你可以这样做:

 new Thread(new Runnable() {
   public void run() {
     final Bitmap bm = getBitmapFromURL(myStation.getStation().imageURL);
     ((Activity) context).runOnUiThread(new Runnable() {
       public void run() {
         icon.setImageBitmap(bm);
       }
     });
   }
 }).start();

这将在活动之外起作用,例如在ListAdapter中。


2

创建一个继承自AsyncTask的类,并在构造函数中传递ImageView。在doInBackground方法中下载图像,在postExecute方法中将图像设置为ImageView。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接