Reputation: 69
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
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.
activity
that contains the fragments.Upvotes: 1