简体   繁体   中英

Show dialog from onPreferenceClick method

I want to display a dialog to the user when she click a preference . I use the following code, from the onPreferenceClick method, which cause the app to stop -

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.pref_general);

    Preference pr = findPreference("advisorsKey");

    pr.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {


            AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(getBaseContext());
            dlgAlert.setMessage("This is an alert with no consequence");
            dlgAlert.setTitle("App Title");
            dlgAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            dlgAlert.setCancelable(true);

            dlgAlert.setPositiveButton("Ok",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            //dismiss the dialog

                        }
                    });

            dlgAlert.create().show();




            return false;
        }
    });

}

What context should I use in the new AlertDialog.Builder(getBaseContext()) call ?

只需使用...

AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);

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