问题
I am working on Night mode for my Android app. I'm using ContextCompat.getColor to get colours programmatically for some UI elements, however this method it's not fetching the correct colour. When the app is in Night mode, so adhering to the night resource qualifier, ContextCompat fetches the color from values/colors.xml and not values-night/colors.xml.
Curiosly, if I call ContextCompat.getColor from an Activity, it returns me the correct color
//get Actual Theme Colors
String bgColor = String.format("#%06X", (0xFFFFFF & ContextCompat.getColor(this, R.color.dialogBackground)));
String txtColor = String.format("#%06X", (0xFFFFFF & ContextCompat.getColor(this, R.color.dialogText)));
Instead, if I call ContextCompat.getColor from a Fragment inside an Activity, it returns the wrong color
//get Actual Theme Colors
bgColor = String.format("#%06X", (0xFFFFFF & ContextCompat.getColor(getActivity(),R.color.dialogBackground)));
txtColor = String.format("#%06X", (0xFFFFFF & ContextCompat.getColor(getActivity(),R.color.dialogText)));
I am using 'androidx.appcompat:appcompat:1.0.2' lib
I don't know if it's related to this bug
I hope you will find a solution or at least a workaround, such as getColor from a resource for a specific configuration (if possibile).
回答1:
Solved the problem, but I am here to help others with same issues.
The strange behavior was caused by a Webview. As stated on this link, when you open for the first time a Webview and then swapping a fragment or adding new views to the UI, they will use the wrong colors, without respecting the night theme. Same issue if you get the color programmatically. I tried some workarounds such as recreate Activity or invalidate resources cache and they actually solved the problem but they are really bad in terms of performance.
Upgrading to androidx.appcompat:appcompat:1.1.0-rc01 fixes the issue, at least partially. If you have some Views without color defined, either in the theme of the app or in the layout xml, then they will still glitch and use wrong colors when launching a webview for the first time and then change fragment. So, you should define every color of your views in the theme of the app using resource variant (-night) for the night colors. If you do this, Views will follow your theme and use the correct colors
TL;DR
Upgrade to androidx.appcompat:appcompat 1.1.0-rc01 or latest
Check if you still have issues
If yes, then set colors for each view you have not defined a color in the theme or xml, using the -night variant for the dark theme
来源:https://stackoverflow.com/questions/57779661/contextcompat-getcolor-method-ignores-night-mode