问题描述
我似乎无法获得android网络视图以使用深色主题或使用
I can't seem to be able to get android web view to use dark theme or use
@media (prefers-color-scheme: dark)
我正在使用具有DayNight主题的AndroidX
I am using AndroidX with DayNight theme
有人在api 29之前有向后兼容的解决方案吗?
Does anyone has a solution that is backward compatible before api 29?
推荐答案
添加到应用程序的build.grade:
Add to your app's build.grade:
implementation "androidx.webkit:webkit:1.2.0"
您可以在此处查看要使用的最新版本:
You can check the latest version to use here:
https://developer.android.com/jetpack/androidx/releases/webkit
如果您具有扩展WebView的类,则将其添加到扩展类的构造函数中:
If you have a class that extends WebView, then add this in your extending class' constructor:
public MyWebView(Context context, AttributeSet attrs) {
super(context, attrs);
...
if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
WebSettingsCompat.setForceDark(getSettings(), WebSettingsCompat.FORCE_DARK_ON);
}
...
}
如果您有一个实例化Web视图的活动,请将其添加到活动的onCreate方法:
If you have an activity that that instantiates a webview, add this to the activity's onCreate method:
myWebView = getViewById(R.id.web_content);
if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
WebSettingsCompat.setForceDark(myWebView.getSettings(),
WebSettingsCompat.FORCE_DARK_ON);
}
当然,您可能需要决定要使用的力量策略:
Of course, you might want to decide which force strategy you want:
WebSettingsCompat.FORCE_DARK_ON
WebSettingsCompat.FORCE_DARK_OFF
WebSettingsCompat.FORCE_DARK_AUTO
这篇关于在网络视图中使用暗模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!