javaandroidrecreate

How to recreate buttons in previous activity?


I have a problem with code in Android Studio.

I have ActivityA and ActivityB.

In ActivityA I have buttons. ActivityB is about settings. For example, I can choose the theme of the app. All done using SharedPreferences.

If I change theme to DARK with this code:

Button Settings = (Button) findViewById(R.id.settings);
Settings.setTextColor(Color.BLACK);     
Settings.setBackgroundResource(R.drawable.shapestylethis3);

and I press back to go o ActivityA - then buttons are changed.

Now when I'm in ActivityB and I wanna change back for theme LIGHT then I would like to get back this default button on ActivityA:

style="@android:style/Widget.Button.Small"

But I don't know how to achieve that. ActivityB is changing right after clicking the button "save" because apart from saving to SharedPreferences I used also recreate(); in onClick.

But when I put recreate() in the onResume in ActivityA, then it's like an infinite loop. I will be really thankful for helping me finding a solution.

Thank you in advance.


Solution

  • You can easily avoid the recrate() going in the infinite loop in your ActivityA using a public static variable or a SharedPreference (any of these two you might prefer).

    Let us have a public static variable in ActivityA like the following.

    public static boolean shouldRecreate = false;
    

    Now when you are changing the style from ActivityB, set the ActivityA.shouldRecreate = true and do not call the recreate().

    Now in the onResume function of your ActivityA check the value of shouldRecreate and call the recreate() function accordingly.

    @Override
    protected void onResume() {
        super.onResume();
    
        if (shouldRecreate) {
            recreate();
            shouldRecreate = false;
        }
    }
    

    Hope that helps!