本文主要是介绍关于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+"%"); } };
这篇关于关于Only the original thread that created a view hierarchy can touch its views.的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!