处理来自其他线程的 UI
我有一个扩展了 Runnable 的类。这个类在不同的线程中执行一些繁重的操作(基本上是从网络下载图像)。我想从此类更新 UI(将下载的图像显示到 ImageView
)。我尝试过使用处理程序但没有成功。这是我的代码:
class DataReceiver implements Runnable
{
public Bitmap bmp;
Public Handler uiHandle;
@Override
public void run()
{
while(true)
{
//do image download process here
}
}
}
在主要活动中
ImageView img = (ImageView)findViewById(R.id.dispImg);
DataReceiver dr=new DataReceiver();
Handler uiHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
updateUI();
}
}
dr.uiHandle = uiHandler;
(new Thread(dr)).start();
public void updateUI()
{
img.setBitmap(dr.bmp);
}
这是更新 UI 的正确方法吗?
I have a class which extends the Runnable
. This class performs some heavy operation (basically downloads the image from network) in different thread. I want to update the UI (display the downloaded image to an ImageView
) from this class. I have tried using handler but did not succeed. Here is my code:
class DataReceiver implements Runnable
{
public Bitmap bmp;
Public Handler uiHandle;
@Override
public void run()
{
while(true)
{
//do image download process here
}
}
}
In main activity
ImageView img = (ImageView)findViewById(R.id.dispImg);
DataReceiver dr=new DataReceiver();
Handler uiHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
updateUI();
}
}
dr.uiHandle = uiHandler;
(new Thread(dr)).start();
public void updateUI()
{
img.setBitmap(dr.bmp);
}
Is it the correct method for updating UI?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以改用 AsyncTask,在 doInBackground 的 run() 中执行当前正在执行的操作,然后在任务的 onPostExecute 中执行 UI 更新。
You could use AsyncTask instead, do what you're currently doing in run() in doInBackground, and then do the UI update in the task's onPostExecute.
几乎;D你需要在类线程上添加该行之前,同时执行:
almost ;D you need on the class thread add the that linebefore while do:
要从另一个线程更新 UI,请使用
To update the UI from another thread use