handler 的post方法解惑

本文解释了在Android开发中如何通过Handler的post方法在子线程中更新UI。文章详细介绍了Handler机制如何确保在非UI线程中执行的任务最终能够在主线程中更新界面元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们在子线程使用handler的post方法时,如下:

new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("UI线程ID2="+Thread.currentThread().getId());
        hh.post(new Runnable() {
            @Override
            public void run() {
             textView2.setText("gaibianle");
                System.out.println("UI线程ID3="+Thread.currentThread().getId());
            }
        }) ;
    }
}

).start();
post方法里面传入 new Runnable 对象,然后在其下面的run方法中,竟然可以操作UI线程,更改ui,对此不少人有疑惑,不是不能在非UI线程更改UI吗?

答案如下:我们传入的new Runnable ,不是新的线程。而是UI线程。

我们在代码中打印当前的线程:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    textView2= (TextView) findViewById(R.id.texthh);
    System.out.println("UI线程ID1="+Thread.currentThread().getId());
    new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("UI线程ID2="+Thread.currentThread().getId());
            hh.post(new Runnable() {
                @Override
                public void run() {
                 textView2.setText("gaibianle");
                    System.out.println("UI线程ID3="+Thread.currentThread().getId());
                }
            }) ;
        }
    }

    ).start();
结果如下:

08-07 22:09:41.673 30533-30533/com.example.cirleimg I/System.out: UI线程ID1=1
08-07 22:09:41.676 30533-30664/com.example.cirleimg I/System.out: UI线程ID2=25480
08-07 22:09:41.743 30533-30533/com.example.cirleimg I/System.out: UI线程ID3=1

所以,handler的Post方法就是直接操作UI线程。


参考:http://www.bkjia.com/Androidjc/893143.html

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值