Changing the theme of an android app using preferences
android
Solution
`setTheme()` is effective only before the layout has been constructed i.e. you should call it before `setContentView()`. The `LayoutInflater` resolves theme attributes and accordingly set properties on the `View`'s it creates. To apply a theme on an already running Activity, you would have to re-start the Activity.
Problem
I have been trying to get my app to read data from the preferences, and change the theme according to the option selected. I have found many different suggestions on the internet, including here, but have been unable to get it to work. I have created preferences.xml and arrays.xml, and the user is able to select the theme they want. However, the change is not reflected in the app. Here are the contents of ActivityMain.java: ``` public class MainActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String userTheme = preferences.getString("prefTheme", "darkab"); if (userTheme.equals("darkab")) setTheme(R.style.darkab); else if (userTheme.equals("light")) setTheme(R.style.light); else if (userTheme.equals("dark")) setTheme(R.style.dark); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @SuppressLint("NewApi") protected void onResume(Bundle savedInstanceState) { recreate(); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String userTheme = preferences.getString("prefTheme", "darkab"); if (userTheme.equals("darkab")) setTheme(R.style.darkab); else if (userTheme.equals("light")) setTheme(R.style.light); else {setTheme(R.style.dark);} super.onResume(); setContentView(R.layout.activity_main); } ``` These are the styles I wish to use, as set in styles.xml: ``` <style name="darkab" parent="android:Theme.Holo.Light.DarkActionBar"></style> <style name="light" parent="android:Theme.Holo.Light"></style> <style name="dark" parent="android:Theme.Holo"> ``` And here is my preferences.java file: ``` public class Preferences extends PreferenceActivity { @SuppressWarnings("deprecation") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } ``` Any help would be appreciated.