Tuesday, 12 February 2019

Cordova Android set windowBackground programmatically at runtime

When the Cordova android app launches, a blank screen is briefly visible before cordova-plugin-splashscreen kicks in. I have learned that this is the windowBackground colour and can be changed by making a custom styles.xml and referencing it within AndroidManifest.xml though the activity's android:theme property. Example:

From AndroidManifest.xml:

<activity android:configChanges="orientation|keyboard|keyboardHidden|screenLayout|screenSize" android:label="@string/activity_name" android:launchMode="singleTask" android:name="MainActivity" android:screenOrientation="portrait" android:theme="@style/CustomStyle" android:windowSoftInputMode="adjustPan">

From styles.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="CustomStyle" parent="@android:style/Theme.Material.Light.NoActionBar">
        <item name="android:windowBackground">@drawable/init_splash</item>
    </style>
</resources>

styles.xml references another file just containing a drawable colour.

This works. It allows me to change the colour that appears before the splash screen.

However, I am now looking to allow the user to optionally change to a dark theme. I have already figured out how to modify cordova-plugin-splashscreen to change the splashscreen based on the user preference, but I'm having trouble changing the windowBackground/theme programatically at runtime.

I have tried adding the following within MainActivity.java or CordovaActivity.java:

setTheme(R.style.CustomDarkStyle);

getWindow().setBackgroundDrawableResource(getResources().getIdentifier("init_splash_dark", "drawable", getPackageName()));

getWindow().setBackgroundDrawable(new ColorDrawable(Color.BLACK));

I placed these in the onCreate before super.onCreate() or setContentView(). The window background colour does indeed change, but the initial blank screen before the splash stays at whatever colour was set in the manifest.

How can I change the activity/window background colour programmatically when the application is started?

Some have suggested changing the app theme to a transparent one to prevent the blank screen entirely, but that causes a delay in opening the app. I'm fine with the blank screen, I just want to change it's colour programmatically.



from Cordova Android set windowBackground programmatically at runtime

No comments:

Post a Comment