How to update activity after using changes from preferences?

When a user opens the settings in my application, he can make changes, for example, changing the theme of the application.

The documentation for ContextThemeWrapper.setTheme(int)states:

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

So, my first thought was to restart the application onResume()when the user changed the settings. However, I noticed that sometimes the process of restarting the activity is seamless, while the activity is closed, the main screen opens and only after a few seconds the application opens again.

I am wondering if there is a way to change the descriptor for setting changes. As, for example, changing the theme after onResumewithout restarting activity or restarting activity in the background when the user is in the settings.

What is the right way to handle this?

+4
source share
4 answers

I assume that you save the theme selected by the user in the application settings. So, in your activity 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 the changes do not take effect until the activity is restarted. Therefore, if you need to immediately apply theme changes, call recreate()after applying the theme:

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

, Attiq, , Threads/AsyncTasks, .

+3

, Preference Activity, , MainActivity paused ( , , stopped). MainActivity onResume(), ; MainActivity , .

+5
When a user opens preferences on my app he may make changes that mean I have to restart my MainActivity however I don't want to user to notice anything happened.

, .

- 1 (MA) TO (PA)

2 (PA) TO

- MA onPause() TO PA onResume()... PA onPause() TO MA onResume()

 nor remove it from the back stack.

, backstack , MainActivity, , , launchmodes

intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
        startActivity(intent);
+1

, , onResume onStart [ ], onCreate(), , .

Point: Re-creating a new action can lead to loss of data retrieved from the network through streams or asynthesis in action, so you also need to accept this problem.

In our application, we save the number of the selected topic in sharedpreferences and load it during the creation of a new activity.

To complete and restart an action

public static void changeToTheme(Activity activity, int theme) {
    sTheme = theme;
    activity.finish();

    activity.startActivity(new Intent(activity, activity.getClass()));
}
+1
source

Source: https://habr.com/ru/post/1569844/


All Articles