关闭

Android 子线程更新UI:handle和runOnUiThread()

标签: androidui线程handle
348人阅读 评论(0) 收藏 举报
分类:

在Android开发中,更新UI只能主线程进行更新,若子线程更新UI,会报错:

E/AndroidRuntime(1516):android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

只有原始的创建视图层次的线程才可以修改它的视图。
主线程之外的线程更新UI有两种方法:handle和runOnUiThread()

界面效果图:
这里写图片描述

1.handle
思路:在主线程onCreate(Bundle savedInstanceState)创建继承Handle的实例,子线程发送handle更新消息,handle实例在handleMessage(Message msg)回调函数中更新UI

public class MainActivity extends Activity implements OnClickListener{
    private TextView tvUpdate;
    private Button btnUpdate;
    private UIHandle mHandle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvUpdate = (TextView)findViewById(R.id.tv_update);
        btnUpdate = (Button)findViewById(R.id.btn_update);
        btnUpdate.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        mHandle = new UIHandle();
        UIThread mThread = new UIThread();
        mThread.start();
    }

    private class UIThread extends Thread{
        @Override
        public void run() {
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("color", "白色");
            msg.setData(data);
            mHandle.sendMessage(msg);
        }
    }

    private class UIHandle extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle dataBundle = msg.getData();
            String color = dataBundle.getString("color");
            tvUpdate.setText(color);
        }   
    }
}

2.使用runOnUiThread(Runnable),把更新UI的代码创建在Runnable中,然后在需要更新UI时,把这个Runnable对象传给runOnUiThread(Runnable)。 这样Runnable对像就能在UI主程序中被调用。如果当前线程是UI线程,那么行动是立即执行。如果当前线程不是UI线程,操作是发布到事件队列的UI线程。

public class MainActivity extends Activity implements OnClickListener{
    private TextView tvUpdate;
    private Button btnUpdate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvUpdate = (TextView)findViewById(R.id.tv_update);
        btnUpdate = (Button)findViewById(R.id.btn_update);
        btnUpdate.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        UIThread mThread = new UIThread();
        mThread.start();
    }

    private class UIThread extends Thread{
        @Override
        public void run() {
            runOnUiThread(new Runnable() {  
                @Override
                public void run() {
                    tvUpdate.setText("白色");
                }
            });
        }
    }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:17072次
    • 积分:395
    • 等级:
    • 排名:千里之外
    • 原创:23篇
    • 转载:1篇
    • 译文:0篇
    • 评论:4条
    文章分类
    最新评论