Change of themes through Java

Asked

Viewed 70 times

2

Hello! I have a java code where I would like to change the Androidmanifest themes according to the return of a certain function.

Example: Having a boolean function that checks the internet connection, the activity will use one theme when the function is true and another when the function is false.

<style name="TemaVerdadeiro" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="TemaFalso" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/branco</item>
    <item name="colorPrimaryDark">@color/branco</item>
    <item name="colorAccent">@color/ERRO</item>
</style>

Is there a command that can choose these themes according to the chosen condition?

1 answer

1

To assign the theme to an Activity use the method setTheme().

Note that the new theme has to be assigned in the method onCreate() and before setContentView().

@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    if(temInternet()){
        setTheme(R.style.TemaVerdadeiro);
    }
    else{
        setTheme(R.style.TemaFalso);
    }

    setContentView(R.layout.activity);

    ......
    ......

}
  • Thank you very much, it will be very useful. Would you have any way to do this after setContentView()? (I mean, while running the activity)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.