开发者

How to open AlertDialog from preference screen?

开发者 https://www.devze.com 2023-02-20 00:50 出处:网络
I am developing Application in androi开发者_JAVA技巧d I want to show AlertDialogif user check the checkboxpreference from preference screen.

I am developing Application in androi开发者_JAVA技巧d I want to show AlertDialog if user check the checkboxpreference from preference screen. so how i can do that..?


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();

      }


}


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!
        }
    }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消