I ran into an interesting little quirk while working on the About dialog for our app.
Android lets you combine groups of settings into styles so you can easily apply them to various UI elements. These styles are often collected into themes that can be applied to change the overall look of the activities in your app.
For example, the Android platform defines a pair of themes for apps to use: a standard dark theme (named Theme), for apps with light text on a dark background; and a standard light theme (named Theme.Light) for apps with dark text on a light background.
We’re using an AlertDialog to display information about the app, and everything works fine when the app is using the normal “dark” theme…but when I changed the app to use Theme.Light, the text on the About screen was rendered as dark grey on a black background, which made it very difficult to read.
I found the solution in a post by Shawn Castrianni, who ran into a similar issue with invisible text in a list on an AlertDialog. It seems Android needs a bit of encouragement to apply the correct style to AlertDialog text.
The solution is pretty simple. I just created a new style, based on the standard Theme.Dialog style that Android uses for dialogs, with an item to set the text to the color that would normally be used on an AlertDialog, like so:
Then it’s just a matter of using that style when creating the AlertDialog.
That itself is a tiny bit tricky, because of how AlertDialogs are normally constructed using a builder pattern; in the case of AlertDialog, the Builder class is hardcoded to use a specific internal style by name. In order to get it to use my style, I had to either not use the builder pattern, or override the theme for the associated context. I chose to do the latter by making use of the ContextThemeWrapper class.
That part was super easy: just create an instance of ContextThemeWrapper that uses your style, and pass that to the Builder instead of the activity context.
So, instead of something like this:
…we now have something like this:
new AlertDialog.Builder(new ContextThemeWrapper(context, R.style.AboutDialog))
There’s one more trick to getting this to work properly, and that’s to make sure you also use the same ContextThemeWrapper if you inflate a custom layout for the AlertDialog.
In our case, I needed to change this:
View view = View.inflate(context, R.layout.about_dialog, null);
View view = View.inflate(new ContextThemeWrapper(context, R.style.AboutDialog), R.layout.about_dialog, null);
Note: If you do not already have an Andromo account register now and start creating Android apps.