关于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+"%");
     }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值