从onPreferenceClick方法显示对话框

时间:2017-10-01 10:03:01

标签: android android-alertdialog onpreferenceclicklistener

我想在点击preference时向用户显示一个对话框。 我使用以下代码,onPreferenceClick方法导致应用停止 -

@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;
        }
    });

}

我应该在new AlertDialog.Builder(getBaseContext())电话中使用哪种上下文?

1 个答案:

答案 0 :(得分:0)

只需使用......

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