echomad 2013-05-13 02:15 采纳率: 100%
浏览 2660
已采纳

求指点,Handler更新UI线程问题

public Handler mHandler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        super.handleMessage(msg);
        switch (msg.what) {
            case 0x123:
                one.setImageResource(imageIds[currentImageId++]);
                two.setImageResource(imageIds[currentImageId1++]);
                three.setImageResource(imageIds[currentImageId2++]);
                four.setImageResource(imageIds[currentImageId3++]);

                if (currentImageId >= imageIds.length) {
                    currentImageId = 0;
                }
                if (currentImageId1 >= imageIds.length) {
                    currentImageId1 = 0;
                }
                if (currentImageId2 >= imageIds.length) {
                    currentImageId2 = 0;
                }
                if (currentImageId3 >= imageIds.length) {
                    currentImageId3 = 0;
                }

                break;

            default:
                break;
        }
        linearLayout.invalidate();
    }

};
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.yaobude);
    initView();

}

public void initView() {
    linearLayout = (LinearLayout)findViewById(R.id.linearlayout);
    one = (ImageView) findViewById(R.id.one);
    two = (ImageView) findViewById(R.id.two);
    three = (ImageView) findViewById(R.id.three);
    four = (ImageView) findViewById(R.id.four);

    one.setOnClickListener(this);
    two.setOnClickListener(this);
    three.setOnClickListener(this);
    four.setOnClickListener(this);

    imageIds = new int[]{
            R.drawable.ee1,R.drawable.ee2,R.drawable.ee3,R.drawable.ee4,R.drawable.mmm2,R.drawable.mmm3
          };

    tt = new TimerTask() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            Message msg = new Message();
            msg.what = 0x123;
            System.out.println("----------"+msg.what);
            mHandler.handleMessage(msg);
        }
    };
    timer.schedule(tt, 0, period);
}

代码如上,为啥还是会报不能更新ui线程的错误呢?求指点 thanks 报错语句:android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

  • 写回答

2条回答 默认 最新

  • echomad 2013-05-13 06:45
    关注

    谢谢楼上 找到原因了 mHandler.handleMessage(msg); - -! mHandler.sendEmptyMessage(msg.what);

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀