子线程更新UI的问题
代码如下:
public class MainActivity extends Activity { private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //第一种情况 button = (Button) this.findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Thread thread = new Thread() { @Override public void run() { Toast.makeText(MainActivity.this, "Click!", 1000) .show(); } }; thread.start(); } }); //第二种情况: Thread thread = new Thread() { @Override public void run() { button = (Button) MainActivity.this.findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Click!", 1000) .show(); } }); } }; thread.start(); //第三种情况 Thread thread1 = new Thread() { @Override public void run() { Toast.makeText(MainActivity.this, "------- Click --------- ", 1000).show(); } }; thread1.start(); }
第一种情况会出现问题:报的错误:
01-07 11:59:10.404: E/AndroidRuntime(4114): FATAL EXCEPTION: Thread-114
01-07 11:59:10.404: E/AndroidRuntime(4114): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
01-07 11:59:10.404: E/AndroidRuntime(4114): at android.os.Handler.<init>(Handler.java:121)
01-07 11:59:10.404: E/AndroidRuntime(4114): at android.widget.Toast$TN.<init>(Toast.java:317)
01-07 11:59:10.404: E/AndroidRuntime(4114): at android.widget.Toast.<init>(Toast.java:91)
01-07 11:59:10.404: E/AndroidRuntime(4114): at android.widget.Toast.makeText(Toast.java:233)
01-07 11:59:10.404: E/AndroidRuntime(4114): at com.example.subthreadtest.MainActivity$1$1.run(MainActivity.java:30)
第二种没有问题:Toast能显示
第三种也会有问题:
01-07 12:03:12.809: E/AndroidRuntime(4664): FATAL EXCEPTION: Thread-129
01-07 12:03:12.809: E/AndroidRuntime(4664): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
01-07 12:03:12.809: E/AndroidRuntime(4664): at android.os.Handler.<init>(Handler.java:121)
01-07 12:03:12.809: E/AndroidRuntime(4664): at android.widget.Toast$TN.<init>(Toast.java:317)
01-07 12:03:12.809: E/AndroidRuntime(4664): at android.widget.Toast.<init>(Toast.java:91)
01-07 12:03:12.809: E/AndroidRuntime(4664): at android.widget.Toast.makeText(Toast.java:233)
01-07 12:03:12.809: E/AndroidRuntime(4664): at com.example.subthreadtest.MainActivity$1.run(MainActivity.java:63)
有错误的情况在Toast前后分别加上:Looper.prepare()和Looper.loop();即可。
可以这样解释:一、三两种情况其实是在子线程中更新了UI,第二种却不是:虽然button在子线程中,但是他是用的主线程的引用。