Change themes through Java

2

Hello! I have a code in java where I would like to change the themes of AndroidManifest 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?

    
asked by anonymous 29.12.2017 / 20:04

1 answer

1

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

Note that the new theme must be assigned in the onCreate() method 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);

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

}
    
30.12.2017 / 13:06