shuaicenglou的博客

博客目的是个人记录和备忘,如有错漏,请认真学习其他教程

关于Only the original thread that created a view hierarchy can touch its views.

今晚写进度条的时候用到了线程,想在子线程里面更新UI组件,给我报了一个

Only the original thread that created a view hierarchy can touch its views.


百度后已解决,记录下来作为备忘

在Android中ui组件不是线程安全的,因此只能在主线程里更新,得使用到Handler机制

代码如下

public class MainActivity extends AppCompatActivity {
    private Button tiao = null;
    private Button yuan = null;
    private ProgressDialog p = null;
    int iCon = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tiao = (Button)super.findViewById(R.id.tiao);
        yuan = (Button)super.findViewById(R.id.yuan);

        tiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                p = new ProgressDialog(MainActivity.this);
                p.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                p.setTitle("正在下载");
                p.setIcon(R.drawable.b);
                p.setProgress(10);
                p.setIndeterminate(false);
                p.setCancelable(true);

                //让进度条显示
                p.show();
                Thread t1 = new Thread(){
                    @Override
                    public void run() {
                        try {
                            while (iCon <= 100) {
                                // 由线程来控制进度。
                                p.setProgress(iCon++);
                                Log.d("fwk----",Integer.toString(iCon));
                                Thread.sleep(500);
                                Message msg = new Message();
                                msg.what = iCon;
                                handler.sendMessage(msg);
                            }
                            p.cancel();
                        }catch(InterruptedException e){
                            e.printStackTrace();
                        }
                    }
                };
       }
    });

}
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            p.setMessage(iCon+"%");
     }
};



阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shuaicenglou3032/article/details/52347739
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭