当用户点击按钮时,一个名为" startAThread"开始,按钮变得不可见。三秒钟后线程完成工作后,按钮再次可见。当用户第二次点击按钮时,它会在LogCat中给出错误:
代码: -
public class MainActivity extends Activity {
Handler mHandler;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
mHandler = new Handler(Looper.getMainLooper());
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
startAthread.start();
button.setVisibility(View.INVISIBLE);
}
});
}
Thread startAthread = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
Thread.sleep(3000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
mHandler.post(new Runnable()
{
@Override
public void run()
{
button.setVisibility(View.VISIBLE);
}
});
}
});
}
logcat的: -
01-10 19:45:39.861 22473-22473/com.guptamanish712.threadtest W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x418002b8)
01-10 19:45:39.891 22473-22473/com.guptamanish712.threadtest E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalThreadStateException: Thread already started.
at java.lang.Thread.start(Thread.java:1045)
at com.guptamanish712.threadtest.MainActivity$1.onClick(MainActivity.java:29)
at android.view.View.performClick(View.java:4295)
at android.view.View$PerformClick.run(View.java:17456)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:174)
at android.app.ActivityThread.main(ActivityThread.java:4952)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mHandler.post(new Runnable() {
@Override
public void run() {
button.setVisibility(View.VISIBLE);
}
});
}
}).start();
button.setVisibility(View.INVISIBLE);
}
});