Uncheck ToggleButton after some period of time

故事扮演 提交于 2019-12-11 23:08:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!