一段时间后取消选中ToggleButton

时间:2012-01-30 00:40:58

标签: java android android-widget 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();
            }

        }
    });
}

1 个答案:

答案 0 :(得分:1)

您只能从主线程更新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();
            }

        }
    });
}