一段时间后取消选中 ToggleButton
我希望我的 ToggleButton 在检查一段时间后不被选中。我正在使用 Timer 和 TimerTask,但当我尝试执行此操作时,我的应用程序总是强制关闭。这是代码:
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();
}
}
});
}
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();
}
}
});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只能从主线程更新 UI。
尝试使用处理程序。
You can only update the UI from the main thread.
Try using a handler.