I am trying to update the app layout based on user preference. After the preference is made, the app requires restart for the preference to come into effect. I want it to happen immediately without restart. Here is my Activity class.

public class MainActivity extends Activity implements OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainactivity);
    SharedPreferences getPrefs = PreferenceManager
            .getDefaultSharedPreferences(getBaseContext());     
    theme  = getPrefs.getString("themelist", "0");
    switch(theme){
    case "0":
        setContentView(R.layout.mainactivity);
        break;
    case "1":
        setContentView(R.layout.mainactivity_black);
        break;
    }       

    initialize();
    setClickListeners();        
}
有帮助吗?

解决方案 2

Its gotta do with the lifecyle of the MainActivity. Problem was that onCreate() method doesn't get called when the main activity returns to focus after preferences are made. So moving the setting of layout to the onStart() or onResume() method solves my problem.

其他提示

In this way you read the preferences at the start-up because you are calling the methods in onCreate. If you want to do something when a change happens you have to register a listner in your activity and unregister it in onDestroy(). See registerOnSharedPreferenceChangeListener() method of SharedPreferences.

This will help you : "MODE_MULTI_PROCESS"

sharedpreferences = context.getSharedPreferences(Utils.WIDG_PREFC, MODE_MULTI_PROCESS);

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top