简体   繁体   中英

Android - stop showing AlertDialog if button already clicked

I need to stop showing the AlertDialog (that is in OnCreate) if the user has alredy pressed that button. I need to disable the AlertDialog if positive button has already been clicked.

AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);
    dlgAlert.setMessage(getString(R.string.dialogMSG));
    dlgAlert.setTitle("App Support Checker");
    dlgAlert.setPositiveButton(R.string.yesdev,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            });

dlgAlert.setCancelable(false);
    dlgAlert.create().show();

You need to point it to somewhere else, I mean some other activity. Otherwise, you can use setNegativeButton instead of setPositiveButton.

dlgAlert.setNegativeButton(R.string.yesdev,
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

            }
        });

Cheers,

Do you mean that on pressing positive button, yu need to remove dialog? By the way you can call dismiss() api for dialog to remove the dialog.

To obtain shared preferences, use the following method In your activity:

SharedPreferences prefs = this.getSharedPreferences( "com.example.app", Context.MODE_PRIVATE); 

To read preferences:

String dateTimeKey = "com.example.app.datetime"; 
long l = prefs.getLong(dateTimeKey, new Date().getTime()); 

To edit and save preferences

Date dt = getSomeDate(); 
prefs.edit().putLong(dateTimeKey, dt.getTime()).commit();

The android sdk's sample directory example of retrieving and stroing shared preferences. It's located in the: /samples/android-/ApiDemo‌​s directory

To store values in shared preferences:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); 
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Sushil"); 
editor.commit(); 

To retrieve values from shared preferences:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); 
String name = preferences.getString("Name",""); 
if(!name.equalsIgnoreCase("")) { 
   name = name+" Jha"; /* Edit the value here*/ 
} 

This is the correct and best way to handle the scenario you are talking about.

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