我试图在再次单击按钮时手动停止线程处理程序。我无法在任何地方获得解决方案,请帮助。
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.black:
changecolor();
Handler h = new Handler();
h.postDelayed( new Runnable() {
@Override
public void run() {
black.setBackgroundResource(R.color.black);
}
}, 2000);
// h.removeCallbacksAndMessages(null);
/*I want to stop the handler here. please help.*/
black.setBackgroundResource(R.color.white);
break;
case R.id.blue:
changecolor();
Handler h1 = new Handler();
h1.postDelayed(new Runnable() {
@Override
public void run() {
blue.setBackgroundResource(R.color.blue);
}
}, 2000);
blue.setBackgroundResource(R.color.white);
break;
case R.id.green:
changecolor();
Handler h2 = new Handler();
h2.postDelayed(new Runnable() {
@Override
public void run() {
green.setBackgroundResource(R.color.green);
}
}, 2000);
green.setBackgroundResource(R.color.white);
break;
case R.id.red:
changecolor();
Handler h3 = new Handler();
h3.postDelayed(new Runnable() {
@Override
public void run() {
red.setBackgroundResource(R.color.red);
}
}, 2000);
red.setBackgroundResource(R.color.white);
break;
}
}
答案 0 :(得分:1)
试试这种方式。
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
@Override
public void run() {
// Put your logic here
}
};
handler.postDelayed(runnable, INTERVAL_TIME);
handler.removeCallbacks(runnable);