Reputation: 33
My app consists of multiple layouts and the layout ends with a finish() to avoid unnecessary reconnection when the back button is touched when switching layouts.
That's why I have an issue where the app reinitializes when turning off or switching the layout even if I change the value of a layout element like setText or setBackgorundColor.
So I would like to keep the theme selected by the user so that it can be used in a PreferenceFragment activity that has changed its value and saved even after exiting the app.
The problem is that in this PreferencFragment java class file I tried to change the values of multiple layouts (setText or setBackground... something more), but nothing works.
Even if I use LayouInflater to get an element from another layout and set the setting to setText, the setting change does not take effect when exiting the PreferencesFragment window.
SettingFragment.java
public class SettingFragment extends PreferenceFragment {
private SharedPreferences pref;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.setting);
pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
}
@Override
public void onResume() {
super.onResume();
pref.registerOnSharedPreferenceChangeListener(listener);
}
@Override
public void onPause() {
super.onPause();
pref.unregisterOnSharedPreferenceChangeListener(listener);
}
SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.activity_main,null);
if(key.equals("theme")){
String datas = pref.getString("theme", null);
if(datas.equals("RED")){
Toast.makeText(getActivity(), "RED!", Toast.LENGTH_SHORT).show();
view.setBackgroundColor(Color.RED); // Nothing To change !!
}
else if(datas.equals("BLUE")){
Toast.makeText(getActivity(), "BLUE!", Toast.LENGTH_SHORT).show();
}
else if(datas.equals("GREEN")){
Toast.makeText(getActivity(), "GREEN!", Toast.LENGTH_SHORT).show();
}
}
}
};
}
Upvotes: 0
Views: 70