标签:
Android的UI操作并不是线程安全的,这就意味着如果有多个线程并发操作UI组件,可能会导致线程安全问题,为了解决这个问题,Android制定了一条简单的规则:只允许UI线程修改Activity里的UI组件,如果其他线程去修改UI组件,则会抛出异常,简单示例演示:
实现点击按钮5秒钟之后,改编TextView的文字。
package cn.lixyz.handlertest; import android.app.Activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { private TextView textView; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.text); button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(){ @Override public void run() { super.run(); try { sleep(5000); textView.setText("改变之后的文字"); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); } }); } }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="30dp" android:text="@string/hello_world" android:textSize="50dp" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="30dp" android:text="点击我改变文字" /> </LinearLayout>
像上面一样编码的话,点击按钮5秒之后,会提示错误:
并抛出异常:
09-15 03:28:33.964 5854-6002/cn.lixyz.handlertest E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-112 Process: cn.lixyz.handlertest, PID: 5854 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6024) at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:820) ......
Android笔记(二十九) Android中的Handler机制
标签:
原文地址:http://www.cnblogs.com/xs104/p/4810970.html