2 echomad echomad 于 2013.05.13 10:15 提问

求指点,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
echomad   2013.05.13 14:45
已采纳

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

suannai0314
suannai0314 你可以点击答案左边的√采纳哦~
4 年多之前 回复
o19830015
o19830015 不客气~
4 年多之前 回复
o19830015
o19830015   2013.05.13 10:25

你可以避开这个错误Thread。

AsyncTask 代替Thread。

或者在ImageView中使用post()。

或者在activity使用runOnUiThread()。

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!