Missael Sanchez
Missael Sanchez

Reputation: 11

ToggleButton changes state when switching fragments

So basically i have a togglebutton in a fragment, the thing is that if i check it(true), whenever I switch to another fragment, and then "come back", the state doesnt save, and i have to check it again, what i want to do is the toggle button to remember its state even after switching fragments. Thanks, hope someone helps.

Here is the code:

    cocina.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {

            if(isChecked){

                ((MainActivity)getActivity()).on2();



                Toast.makeText(getActivity(),"On",Toast.LENGTH_SHORT).show();
            }

            else{
                ((MainActivity)getActivity()).off2();

                Toast.makeText(getActivity(),"Off",Toast.LENGTH_SHORT).show();
            }
        }
    });

Upvotes: 0

Views: 780

Answers (2)

Jaythaking
Jaythaking

Reputation: 2102

I would avoid using static values as much as possible so the value could survive the app Lifecycle. I'd put the boolean value in SharedPreference and retrieve it back onCreateView of the Fragment like this:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();


cocina.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {

        if(isChecked){
            editor.putBoolean("switchValue", true).commit();
            Toast.makeText(getActivity(),"On",Toast.LENGTH_SHORT).show();
        }

        else{
            editor.putBoolean("switchValue", false).commit();
            Toast.makeText(getActivity(),"Off",Toast.LENGTH_SHORT).show();
        }
    }
});

and to retrieve the value whenever you needs it:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean default = sharedPref.getBoolean("switchValue", false);

Upvotes: 1

pawar
pawar

Reputation: 70

You can take a static boolean the value of which will be set to true or false accordingly the state of the toogle Switch. And on create view of fragment you can apply the condition that if boolean b(say) is false so Switch.setChecked(b).

Upvotes: 0

Related Questions