Emi
Emi

Reputation: 1

how to show dialog only once in Kotlin?

When opening my app a dialog is always shown that closes when you press "Ok", I would like it to only be shown the first time they open the app, this is my code:

val miDialogo = AlertDialog.Builder(this)
    miDialogo.setTitle(R.string.dialogo_titulo)
    miDialogo.setMessage(R.string.dialogo_mensage)
    miDialogo.setPositiveButton("Ok", null)
    val dialog = miDialogo.create()
    dialog.show()

Upvotes: 0

Views: 729

Answers (1)

Hamed Goharshad
Hamed Goharshad

Reputation: 661

You can save a boolean in SharedPreferences and check it before showing the dialogue if user saw it once switch it to false.

   fun isFirstRun() {

    var prefs_name = "MyPrefsFile"
    var isFirst = false

    var prefs: SharedPreferences = getSharedPreferences(prefs_name, MODE_PRIVATE)
    var isFirst: Boolean = prefs.getBoolean(prefs_name, false)

    if (isFirst) {
    //Show the dialogue 

     prefs.edit().putInt(prefs_name, 
     false).apply();
    }
   }

Upvotes: 1

Related Questions