0

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();        
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
John Smith
  • 418
  • 7
  • 21

3 Answers3

0

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.

greywolf82
  • 21,813
  • 18
  • 54
  • 108
  • Just an example, see the first response: http://stackoverflow.com/questions/7020446/android-registeronsharedpreferencechangelistener-causes-crash-in-a-custom-view – greywolf82 Apr 20 '14 at 14:57
  • The registerOnSharedPreferenceChangeListener() and unregisterOnSharedPreferenceChangeListener() preference listeners don't help. I tried. – John Smith Apr 20 '14 at 19:21
  • I think your problem is with the theme at runtime not the shared preferences. See here: http://stackoverflow.com/questions/11421223/change-and-apply-theme-at-runtime-in-android – greywolf82 Apr 21 '14 at 07:18
0

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.

John Smith
  • 418
  • 7
  • 21
-1

This will help you : "MODE_MULTI_PROCESS"

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