一段时间后取消选中

一段时间后取消选中

我希望一段时间后取消选中我的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();
            }

        }
    });
}

最佳答案

您只能从主线程更新UI。

尝试使用处理程序。

@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();
            }

        }
    });
}

07-27 21:46