【安卓】使用Handler完成子线程更新ui

非常简洁的代码:

public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable(){
@Override
public void run() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
           @Override
           public void run() {
            ((TextView) findViewById(R.id.button1)).setText("子线程更新ui");
           }
       });
}
}).start();
}
}

使用Handler的Post方法,传递一个Runnable的对象,post方法在android api文档中是这么描述的:

Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.

也就是说子线程把更新ui的操作通过handler传递给ui线程,然后会被自动执行,更新ui就这么愉快的被完成啦~!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值