通过css注入实现的android webview的夜间模式

    xiaoxiao2025-10-21  9

    一开始,产品跟我确认是否能够实现uc的夜间模式,我回答,当然可以,uc可以,我们也可以。

    但是后来发现不是酱紫的,找了很多方法都不能做到uc那样,最后找到一些方法就是webview调用js、

    当然,这个方案也不能做到像uc那样完美,但相对来说,勉勉强强,应该比调节亮度的应该要好些

    原理就是在webview的加载结束,调用css代码,改变html页面的背景色、文字颜色、边框颜色等。

    night.css代码如下

    div,section,ul,li,a,h1,h2,h3,p,link,textarea,form,select,input,span,button,em,menu,aside,table,tr,td,nav,img,dl,dt,dd, html, body,strong{     background:#222222 !important;color:#888888!important;     border-color:#555555 !important;     scrollbar-arrow-color:#CCCCCC !important;     scrollbar-base-color:#222222 !important;     scrollbar-shadow-color:#222222 !important;     scrollbar-face-color:#222222 !important;     scrollbar-highlight-color:#222222 !important;     scrollbar-dark-shadow-color:#222222 !important;     scrollbar-3d-light-color:#222222 !important;     scrollbar-track-color:#222222 !important;} strong{display:block;} a,a *{color:#888888 !important;text-decoration:none !important;}a:visited,a:visited *,a:active,a:active *{color:#555555 !important;} a:hover,a:hover *{color:#888888 !important;     background:#222222 !important;} input,select,option,button,textarea{color:#888888 !important;     background:#222222 !important;     border:#555555 !important;     border-color: #888888 #888888 #888888 #888888 !important;} input:focus,select:focus,option:focus,button:focus,textarea:focus,input:hover,input[type=button],input[type=submit],input[type=reset],input[type=image] {border-color: #888888 #888888 #888888 #888888 !important;} input[type=button]:focus,input[type=submit]:focus,input[type=reset]:focus,input[type=image]:focus, input[type=button]:hover,input[type=submit]:hover,input[type=reset]:hover,input[type=image]:hover {color:#888888 !important;background:#222222 !important; border-color: #888888 #888888 #888888 #888888 !important;}

    在webview加载结束onPageFinished时调用

    if( nightCode == null ) { InputStream is = getResources().openRawResource( R.raw.night ); byte[] buffer = new byte[is.available()]; is.read( buffer ); is.close(); nightCode = Base64.encodeToString( buffer , Base64.NO_WRAP ); } mWebView.loadUrl( "javascript:(function() {" + "var parent = document.getElementsByTagName('head').item(0);" + "var style = document.createElement('style');" + "style.type = 'text/css';" + "style.innerHTML = window.atob('" + nightCode + "');" + "parent.appendChild(style)" + "})();" );

    就可以实现夜间模式啦,如果想再设置回来,就在调用一下日间模式的day.css.

    在调用css成功后,有遇到过一个问题,发现粗体的文字在调用css过程中会被截掉,只显示上面一半文字,,想不明白啊,后来通过方法把网页源码给打印出来,发现那些粗体有问题的文字都用strong给包起来了,后来加上strong{display:block;}就ok啦。

    获取网页源码的方法:http://www.cnblogs.com/zhwl/archive/2013/10/18/3375775.html

    网页中的方法如果没有打印出来,是在showSource方法上少加了@JavascriptInterface

    最后,下载资源见:http://download.csdn.net/download/shuishuixiaoping/10168280。

    第一次写博客,勿喷哦~~~~

    转载请注明原文地址: https://ju.6miu.com/read-1303375.html
    最新回复(0)