问题是当我点击第二个按钮时,我的应用程序崩溃,我不明白为什么。当我第二次碰到按钮时,再次假设相同。
感谢任何帮助。
public class main extends Activity {
Boolean grabar = false;
TextView texto;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
texto = (TextView) findViewById(R.id.texto);
Button startbtn = (Button) findViewById(R.id.button);
startbtn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
background.start();
}
});
}
Thread background = new Thread (new Runnable() {
public void run() {
try {
Thread.sleep(3000);
cambiarHandler.sendEmptyMessage(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Handler cambiarHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
texto.setText("ok");
}
};
}
答案 0 :(得分:4)
我看到的问题是线程被设计为运行一次。每次要运行它时,都需要创建一个新的线程实例。
答案 1 :(得分:0)
答案 2 :(得分:0)
我不知道抛出了哪个异常。我想这是NPE抛出的。当您尝试将文本设置为TextView
时。尝试在TextView
方法中实例化handleMessage()
:
Handler cambiarHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
texto = (TextView) findViewById(R.id.texto);
texto.setText("ok");
}
};
在onClick方法中,每次单击按钮时都要执行此线程的新实例。
public void onClick(View v){
new Thread (new Runnable() {
public void run() {
try {
Thread.sleep(3000);
cambiarHandler.sendEmptyMessage(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}