首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Android进阶-Handler的应用-Only the original thread that created a view hierarchy can touch its views

Android进阶-Handler的应用-Only the original thread that created a view hierarchy can touch its views

作者头像
圆号本昊
发布2021-09-24 12:20:59
发布2021-09-24 12:20:59
1.3K0
举报
文章被收录于专栏:github@hornhuanggithub@hornhuang

众所周知,在 Thread( 线程 )中,直接更新布局控件的内容是不被允许的,当今天出现了一个状况,我在 Handle 中更新碎片的 TextView 内容竟然给我抱了哥错:Only the original thread that created a view hierarchy can touch its views

根本原因

因为非UI线程做了UI操作,进而报出了 Only the original thread that created a view hierarchy can touch its views。


解决方案

安排 messages 和 runnables 在将来的某个时间点执行 和将action入队以备在一个不同的线程中执行。也就是说,将更新 UI 的待爱吗写在一个 Runnable 中,然后调用 Handle 的 post 方法,就能使线程更新。范例:

代码语言:javascript
复制
    private Handler handler = new Handler();
    private Thread thread = new Thread(){
        @Override
        public void run() {
            while (true){
                handler.post(runnable);
                try {
                    sleep(60000);// 没一分钟看下事件
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            mTips.setText("已打卡: " + time + " 分钟");
        }
    };

具体实例代码:

com/example/joker/signinsystem/fragment/personal.java --> 点击跳转 —— https://github.com/FishInWater-1999/android-SignInSystem/blob/master/app/src/main/java/com/example/joker/signinsystem/fragments/Personal.java

欢迎关注我获得跟多小姿势~~~

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/05/05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 根本原因
  • 解决方案
  • 具体实例代码:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档