gpt4 book ai didi

Android CheckBox 在恢复 fragment 状态时不监听 OnCheckedChangeListener

转载 作者:行者123 更新时间:2023-12-04 01:48:54 31 4
gpt4 key购买 nike

在我的 android 应用程序中,我有 fragment ,在其中一个 fragment 中,我有复选框。这个复选框有这样的监听器,在检查时显示警告对话框:

@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
alertDialog.setPositiveButton(R.string.is_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
NItem item = new NItem();
item.isOk = 1;
setItem(item);
}
});
alertDialog.setNegativeButton(R.string.is_not_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
NItem item = new NItem();
item.isOk = 0;
setItem(item);
}
});
alertDialog.show();
}
}

当我选中checkbox并转到other fragment并返回fragment时,这个checkbox,方法 onCheckedChanged 被再次调用。我认为这是因为 fragment 保存状态 恢复。如何预防?

最佳答案

您应该检测用户何时触摸您的复选框,并且仅在复选框被选中时处理onCheckedChanged()感动。

这是一个例子:

static Boolean isTouched = false;

yourCheckbox.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
isTouched = true;
return false;
}
});


//Listen to checked change, but only if the toggle is touched, not when initializing the toogle
yourCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isTouched) {
//Do your things
isTouched = false;
}
}
});

关于Android CheckBox 在恢复 fragment 状态时不监听 OnCheckedChangeListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54213763/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com