How to recover the status of a button with Sharedpreferences on Android/Kotlin on multiple screens?

Asked

Viewed 195 times

0

Friends, I have two activitys, at first I have a sound button on and off and at second I have some buttons like a name button A and when clicked it should know what the state of the sound button is at first Activity... if at first Activity the off and on button is at status on the A button shall make the sound or otherwise when it is switched off. It turns out that a few days ago I’ve been trying and still can’t solve. What do you say to me? I’m waiting for a position.

First screen

This method is on the first screen where save preferences, or at least I thought it saved...

[Primeira tela[1]

   open fun toChangeButtonVolume() {


    volume_play_menu.setOnClickListener({


        v -> v.isSelected = !v.isSelected

        if (v.isSelected) {
            v.setBackgroundResource(R.drawable.volume_ligado)
            val prefs = getSharedPreferences("preferencias", Context.MODE_PRIVATE)

            val ed = prefs.edit()

            ed.putInt("chave", 1)

            ed.commit()
        }

        else {

            v.setBackgroundResource(R.drawable.volume_mudo)
        }
    })

Second screen This method gets in the second screen when I try to recover the preferences created on the first screen. The name button abc_learn_a should emit sound depending on the status of the button created in the first Activity.

fun goFirstLetter( ) {

    abc_aprender_a.setOnClickListener({

        v ->
        v.setBackgroundResource(R.drawable.check)

        val prefs = getSharedPreferences("preferencias", Context.MODE_PRIVATE)
        //Imagino que aqui eu consiga recuperar a chave na primeira tela ou deveria pelo menos 

        val boo = prefs.getInt("chave", 1)
         playSoundInButton()

inserir a descrição da imagem aqui

1 answer

0


if (v.isSelected) {
   v.setBackgroundResource(R.drawable.volume_ligado)
} else {
   v.setBackgroundResource(R.drawable.volume_mudo)
}

val prefs = getSharedPreferences("preferencias", Context.MODE_PRIVATE)
val ed = prefs.edit()
ed.putBoolean("chave", v.isSelected)
ed.commit()

abc_aprender_a.setOnClickListener({  v ->
   v.setBackgroundResource(R.drawable.check)
   val prefs = getSharedPreferences("preferencias", Context.MODE_PRIVATE)
   val boo = prefs.getBoolean("chave", true)
   if(boo){
       playSoundInButton()
   }
}
  • 1

    Try it like this, it should work :D

  • 1

    Another option is to pass the status of the button via Intent (muted or not muted)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.