How can you keep a Switch Button ON in android studio?

0

Good morning folks, I have the following problem: I have a switch button that when I turn it ON starts playing an mp3 file, so all right, the problem is that when I change the screen (ie I change the orientation) and I go back to return to the screen in which I had the switch button, it appears as OFF, my question is if there is any way to keep it ON when I change the screen and return to it.

This is my code:

swtMusic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked){

                mp.start();

                swtMusic.setSaveEnabled(true);
            }
            else{

                mp.stop();
                swtMusic.setChecked(false);
            }
        }

    });
    
asked by Juampi 29.11.2017 в 16:03
source

2 answers

0

It's easy to use two methods in your class to save your data, obviously it's not the only way but it's the one I've personally tried

@Override
protected void onSaveInstanceState(Bundle outState){
    super.onSaveInstanceState(outState);
    outState.putInt("estado", switch.isChecked());
}

and in second method

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
    super.onRestoreInstanceState(savedInstanceState);
    cont = savedInstanceState.getBool("estado");
    switch.setChecked(cont);
}
    
answered by 29.11.2017 в 16:16
0

the partner's question is simple:

  

There is some way to keep it ON when I change the screen and   return to it.

I confirm, if there are several ways to keep the button ON when you change activity or when the activity for a rotation is recreated.

Now as the question is very open to provide a specific solution ... I am sure that many times it happens to developers who do not know how to ask something because we do not know how things work.

I recommend you take a look at these two documents on storage and life cycles of an activity. They will help you understand how it works and why it happens what you describe in your question.

About storage or persistence of data: this link helps you to know what options are available to save data even if the application is closed. link

About life cycles: this link helps you to understand that activities have life cycles and when launching a new activity as is your case, the activity from where you launch changes state, likewise happens if there is a rotation change. link

Take the time to read these links are very useful and can guide you to the answer or at least to better formulate your question.

Greetings!

    
answered by 29.11.2017 в 17:39