今晚写进度条的时候用到了线程,想在子线程里面更新UI组件,给我报了一个
Only the original thread that created a view hierarchy can touch its views.
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+"%"); } };