Switch does not persist

I made a switch in a fragment, that uses a fragment layout in the MainActivity. The fragment layout is shared(alternatively) by four fragments. It uses a method loadFragment() that changes between the fragments.

In one of the frags, there's a switch button, but whenever I change between the fragment, the switch does not persist its state. How do I make it persist? I've tried SharedPreferences.

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_mufradat_harian, container, false);

    mufradatSwitch = v.findViewById(R.id.switchMufradat);
    mufradatSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(mufradatSwitch.isChecked()){
                SharedPreferences pres = PreferenceManager.getDefaultSharedPreferences(getContext());
                Boolean checked = pres.edit().putBoolean("checked", true).commit();
            }else{
                SharedPreferences pres = PreferenceManager.getDefaultSharedPreferences(getContext());
                Boolean checked = pres.edit().putBoolean("checked", false).commit();

            }

        }
    });

    return v;
}

Thank you.

Upvotes: 0

Views: 48

Answers (1)

Khalid Taha
Khalid Taha

Reputation: 3313

This is not a problem, this is the normal behavior since you recreate the fragment each time. But in order to keep the state of the switch button, you need to save the state into a model that will not be changed which should be inside your Activity and pass this model to the fragment in order to get the state of the switch button from this model and give it to the switch button.

  1. Create a model that contains the persist data.
  2. Add this model in the activity that contains the fragments.
  3. Pass this model to the fragment that contains the switch.
  4. Set the state of the switch to that inside the model.
  5. When changing the switch state, change the value inside the model to the new state.

Upvotes: 1

Related Questions