Android Question Best practice for Android Dark theme?

jo1234

Active Member
Licensed User
Longtime User
Hi all,

I have a question concerning the Dark theme that has been introduced with Android 10.
What is the best practice to support Dark themes in B4A?
How can I select an image based on the night mode flag?

thanks a lot,
Johannes
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
You can use AppCompat for this and set the theme to be:
B4X:
CreateResource(values, theme.xml,
<resources>
    <style name="MyAppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
    </style>
</resources>
)

If you use the default colors then most views will look properly automatically.

You can check whether night mode is active:
B4X:
Sub IsNightMode As Boolean
   Dim ctxt As JavaObject
   ctxt.InitializeContext
   Log(ctxt.RunMethodJO("getResources", Null).RunMethodJO("getConfiguration", Null).GetField("uiMode"))
   Return Bit.And(ctxt.RunMethodJO("getResources", Null).RunMethodJO("getConfiguration", Null).GetField("uiMode"), 0x30) = 0x20
End Sub

You can set the default night mode if you don't want it to be based on the system default:
B4X:
Sub SetDefaultNightMode (Mode As Int)
   Dim jo As JavaObject
   jo.InitializeStatic("androidx.appcompat.app.AppCompatDelegate").RunMethod("setDefaultNightMode", Array(Mode))
End Sub

The constants are listed here: https://developer.android.com/refer...at/app/AppCompatDelegate.html#MODE_NIGHT_AUTO

Note that the activity will be recreated if the theme changes.
 
Upvote 0

Similar Threads

Top