您应该创建一个自定义复选框并覆盖它的切换方法以对状态执行任何操作。以下是一些示例功能的基本代码:
在 xml 中,如下声明您的自定义视图(更改您的包名称):
<com.example.mike.myapplication.CustomCheckBox
android:id="@+id/my_checkbox"
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
然后在你的Activity/fragment中初始化它:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
cb = (CustomCheckBox) findViewById(R.id.my_checkbox);
// You should ALWAYS add this listener!!!!
cb.addListener(new CustomCheckedChangeListener() {
@Override
public void onConfirmCheckDisable() {
buildDialog();
}
});
}
private void buildDialog() {
new AlertDialog.Builder(this)
.setTitle("Confirm")
.setMessage("Are you sure you want to uncheck this entry?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
cb.setChecked(false);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
这是您的自定义复选框类:
public class CustomCheckBox extends CheckBox {
private CustomCheckedChangeListener mListener;
public CustomCheckBox(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomCheckBox(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public CustomCheckBox(Context context) {
super(context);
}
public void addListener(CustomCheckedChangeListener list){
mListener = list;
}
@Override
public void toggle() {
if (mListener == null) return;
if (isChecked()) {
mListener.onConfirmCheckDisable();
} else {
super.toggle();
}
}
}
这是你的听众:
public interface CustomCheckedChangeListener {
public void onConfirmCheckDisable();
}
这有帮助吗?