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

在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("白色");
                }
            });
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值