我有这个代码,当checkBox被选中时,editTexts会得到时间(当时间改变时刷新)但是当我取消选中它时,它会将editText设置为空白,它似乎不适用于我打算做的事情
check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(check.isChecked()){
final Handler someHandler = new Handler(getMainLooper());
someHandler.postDelayed(new Runnable() {
@Override
public void run() {
editTimeOut.setText(new SimpleDateFormat("HH:mm", Locale.US).format(new Date()));
someHandler.postDelayed(this, 1000);
}
}, 10);
}
else{
editTimeOut.setText("");
}
}
});
答案 0 :(得分:0)
您每秒都在更新edittext而不是取消它。一个简单的解决方法是检查runnable中是否有isChecked。需要进行一些重构的更好的解决方案是删除runnable。
简单修复:
if(check.isChecked()){
final Handler someHandler = new Handler(getMainLooper());
someHandler.postDelayed(new Runnable() {
@Override
public void run() {
if(check.isChecked()){
editTimeOut.setText(new SimpleDateFormat("HH:mm", Locale.US).format(new Date()));
someHandler.postDelayed(this, 1000);
}
}
}, 10);
}
更好的解决方法:
final Handler someHandler = new Handler(getMainLooper());
Runnable timeoutRunnable = new Runnable() {
@Override
public void run() {
editTimeOut.setText(new SimpleDateFormat("HH:mm", Locale.US).format(new Date()));
someHandler.postDelayed(this, 1000);
}
};
check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(check.isChecked()){
someHandler.postDelayed(timeoutRunnable, 10);
} else{
someHandler.removeCallbacks(timeoutRunnable);
editTimeOut.setText("");
}
}