Android(安卓)更新UI的两种方法——handler和runOnUiThread()
16lz
2022-06-10
Android 更新UI的两种方法——handler和runOnUiThread()
在Android开发过程中,常需要更新界面的UI。而更新UI是要主线程来更新的,即UI线程更新。如果在主线线程之外的线程中直接更新页面显示常会报错。抛出异常:android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
只有原始创建这个视图层次(view hierachy)的线程才能修改它的视图(view)
话不多说,贴出下面的代码
方法一:
在Activity.onCreate(Bundle savedInstanceState)中创建一个Handler类的实例, 在这个Handler实例的handleMessage回调函数中调用更新界面显示的函数。
界面:
- <spanstyle="font-size:14px;">publicclassMainActivityextendsActivity{
- privateEditTextUITxt;
- privateButtonupdateUIBtn;
- privateUIHandlerUIhandler;
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- UITxt=(EditText)findViewById(R.id.ui_txt);
- updateUIBtn=(Button)findViewById(R.id.update_ui_btn);
- updateUIBtn.setOnClickListener(newView.OnClickListener(){
- publicvoidonClick(Viewv){
- //TODOAuto-generatedmethodstub
- UIhandler=newUIHandler();
- UIThreadthread=newUIThread();
- thread.start();
- }
- });
- }
- @Override
- publicbooleanonCreateOptionsMenu(Menumenu){
- getMenuInflater().inflate(R.menu.activity_main,menu);
- returntrue;
- }
- privateclassUIHandlerextendsHandler{
- @Override
- publicvoidhandleMessage(Messagemsg){
- //TODOAuto-generatedmethodstub
- super.handleMessage(msg);
- Bundlebundle=msg.getData();
- Stringcolor=bundle.getString("color");
- UITxt.setText(color);
- }
- }
- privateclassUIThreadextendsThread{
- @Override
- publicvoidrun(){
- try{
- Thread.sleep(3000);
- }catch(InterruptedExceptione){
- //TODOAuto-generatedcatchblock
- e.printStackTrace();
- }
- Messagemsg=newMessage();
- Bundlebundle=newBundle();
- bundle.putString("color","黄色");
- msg.setData(bundle);
- MainActivity.this.UIhandler.sendMessage(msg);
- }
- }
- }</span>
方法二:利用Activity.runOnUiThread(Runnable)把更新ui的代码创建在Runnable中,然后在需要更新ui时,把这个Runnable对象传给Activity.runOnUiThread(Runnable)。 这样Runnable对像就能在ui程序中被调用。如果当前线程是UI线程,那么行动是立即执行。如果当前线程不是UI线程,操作是发布到事件队列的UI线程
[html] view plain copy
- FusionField.currentActivity.runOnUiThread(newRunnable()
- {
- publicvoidrun()
- {
- Toast.makeText(getApplicationContext(),,"UpdateMyUI",
- Toast.LENGTH_LONG).show();
- }
- });
更多相关文章
- Only the original thread that created a view hierarchy can t
- Android之adt 23找不到NDK路径设置解决方案
- Android界面布局基本属性
- Android新线程中更新主线程UI中的View方法汇总
- AOSP和Chromium的Android(安卓)WebViewTest
- Android(安卓)SDK下载和更新失败的解决方法!!!
- Android应用程序执行流程
- Android性能调优
- 更新Activity的几个方法