简体   繁体   中英

Android how to show pop up on clicking CheckBoxPreference

I have a PreferenceScreen in which i have a checkbox with the following code:

<CheckBoxPreference
        android:defaultValue="false"
        android:key="the_key"
        android:summary="Random text here."
        android:title="My Title"
        />

I want a pop up message to be displayed on click of this checkbox that will have a set button and a cancel. If "set" will be pressed then the checkbox will be checked if previously unchecked and the opposite. How can i do that? Here is the code of my pop up message.

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    // Use the Builder class for convenient dialog construction
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setMessage("Some message that will be displayed")
            .setPositiveButton(R.string.set, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // do something
                }
            })
            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // User cancelled the dialog
                }
            });
    // Create the AlertDialog object and return it
    return builder.create();
}

Also how can i get the value of my checkbox(checked or not)? Thanks!!

To get checkbox is checked or not from CheckBoxPreference, use this

CheckBoxPreference pref = (CheckBoxPreference) findPreference("checkbox_preference");
pref.isChecked(); //returns if it is checked or not

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM