I am developing Application in android I want to show AlertDialog if user check the checkboxpreference from preference screen. so how i can do that..?
Asked
Active
Viewed 1.5k times
15
-
1It would help significantly if you let us know what technology and platform you are using. Please always provide as much context as you practically can. – Iain Ballard Mar 28 '11 at 09:28
-
1It has an Android tag... – Zsombor Erdődy-Nagy Mar 28 '11 at 09:38
-
possible duplicate of [How to open AlertDialog from preference screen?](http://stackoverflow.com/questions/5457944/how-to-open-alertdialog-from-preference-screen) – Roman Nurik Apr 02 '11 at 17:19
3 Answers
16
Try this one ...
public class MyPreferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
final Preference preference) {
if(preference.equals("MyCheckboxPreferenceKey")) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Message");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//action on dialog close
}
});
builder.show();
}
}

Michael Mrozek
- 169,610
- 28
- 168
- 175

Vaibhav Jani
- 12,428
- 10
- 61
- 73
-
1@Dharmendra Actually, this requires a return statement and will require the main part of the method below to be added to cover "unimplemented methods" – Abandoned Cart Jul 30 '12 at 16:56
-
I had up-voted this along the way , but coming back to it .. I am having an issue where method onPreferenceTreeClick() is not getting called. I found this post for current solution that helped me get this logic working http://stackoverflow.com/a/12325780/2162226 – Gene Bo May 06 '15 at 19:35
1
Override onSharedPreferenceChanged
in your PreferenceActivity
class:
public class MyPreferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
...
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("MyCheckboxPreferenceKey")) {
//Show your AlertDialog here!
}
}

GrAnd
- 10,141
- 3
- 31
- 43
0
public class MyPreferences extends PreferenceActivity{
...
//getting current context for builder
AlertDialog.Builder build = new AlertDialog.Builder(this);
//setting some title text
build.setTitle("SomeTitle");
//setting radiobuttons list
build.setSingleChoiceItems(new String[]{"One", "Two"}, 0, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Some behavior here
}
});
build.setNegativeButton("Cancel", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Might be empty
}
});
//creating dialog and showing
AlertDialog dialog = build.create();
dialog.show();
}
That's all.

user1600401
- 37
- 1
- 3