问题
I want my ToggleButton to be unchecked after some period of time when i check it. I am using Timer and TimerTask but my application always force close when i try to do this. This is the code:
public class Vjezba5Activity extends Activity {
TimerTask TimerTask11;
Timer timer1 = new Timer();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ToggleButton TB1 = (ToggleButton) findViewById(R.id.toggleButton1);
TB1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (TB1.isChecked()){
TimerTask11 = new TimerTask() {
public void run() {
TB1.setChecked(false);
}
};
timer1.schedule(TimerTask11, 1000);
}
else {
Toast.makeText(Vjezba5Activity.this, "Uncheck", Toast.LENGTH_SHORT).show();
}
}
});
}
回答1:
You can only update the UI from the main thread.
Try using a handler.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ToggleButton TB1 = (ToggleButton) findViewById(R.id.toggleButton1);
Handler handler = new Handler();
TB1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (TB1.isChecked()){
handler.postDelayed(new Runnable() {
public void run() {
TB1.setChecked(false);
}
}, 1000);
}
else {
Toast.makeText(Vjezba5Activity.this, "Uncheck", Toast.LENGTH_SHORT).show();
}
}
});
}
来源:https://stackoverflow.com/questions/9058179/uncheck-togglebutton-after-some-period-of-time