Search code examples
androidpreferences

How to update activity after uses changes appearance from preferences?


When a user opens preferences on my app he may make changes for example changing the app theme.

The documentation for ContextThemeWrapper.setTheme(int) says:

Set the base theme for this context. Note that this should be called before any views are instantiated in the Context (for example before calling setContentView(View) or inflate(int, ViewGroup)).

So my first thought was restarting the app onResume() when the user changed the preferences. However I noticed that sometimes the process of restarting the activity is seamless while other times the activity is closed, the home screen is seen and only after some seconds the app opens again.

I'm wondering if there is a way to change handle the preferences changes. Like for instance changing the theme after onResume without restarting the activity or restarting the activity on the background while the user is on preferences.

What's the right way to handle this?


Solution

  • I'm assuming you are storing user's selected theme in App Preferences. So in your Activity's onCreate(), add setTheme().

    public void onCreate(Bundle savedInstanceState) {
        setTheme(android.R.style.Theme); // or whatever theme you're using
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }
    

    But changes don't take effect until the activity is restarted. So if you need to immediately apply theme changes, call recreate() afterwards applying theme:

    // Might need to call them on getApplication() depending on Context
    setTheme(userSelectedTheme);
    recreate();
    

    Also, as Attiq mentioned, re-creating an activity might result in loss of data fetched from network using Threads/AsyncTasks so you need to take that in to account as well.