Android record 24-webview for daytime/night reading mode

Source: Internet
Author: User

Objective

This blog to share a WebView use case, the implementation of Android calls JavaScript code to control Day/night mode. about how to use WebView, the official website has a good description, Building Web Apps in WebView, the wizard here is not much to repeat.

Implementation ideas

Unlike the native application, we can simply implement invoking the system API to achieve that by styling the theme. If our content is HTML content, how to achieve? The first load of HTML page is definitely to use WebView, through the Loadurl method can display HTML page to WebView, we know that Android can interact with JavaScript, That means you can call Android code in JavaScript, or you can invoke JavaScript code in Android, so there's a thought Use the JavaScript code in the HTML page of Android to control the page background and font style to switch between day/night mode .

How to implement provide a test HTML code
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01//en" "HTTP://WWW.W3.ORG/TR/HTML4/STRICT.DTD";><html><meta http-equiv="Content-type" Content="text/html; Charset=utf-8 ">    <script language=JavaScript>  function load_night() { document.bgcolor="#000000"var    FontColor = document.getElementById ("Font"); if (!fontcolor)    { return; } fontcolor.style.color="white"}    </script><script language="javascript">  function load_day(){ document.bgcolor="#ffffff"var    FontColor = document.getElementById ("Font"); if (!fontcolor)        { return; } fontcolor.style.color="Black" }            </script><head><title>WebView Test Night Mode</title></head><body LEFTMARGIN="Ten" vlink= "#8000FF" BGCOLOR="# FFFFFF " ALINK=" #FF0000 " LINK=" #0000FF "TOPMARGIN= "Ten" TEXT="#666666">    <div id="Font">Dwarfed by the pale</div>    </br>    <button type="button" onClick="Load_night ()">Night mode</button>    <button type="button" onClick="Load_day ()"> Daytime mode</button></body></html>
Loading HTML pages
WebSettings settings = webView.getSettings();// 设置javaScript可用settings.setJavaScriptEnabled(true);webView.loadUrl("file:///android_asset/01.html");
Android calls JavaScript code
@Override    publicvoidonClick(View v) {        switch (v.getId()) {        case R.id.btn_nightmode:            webView.loadUrl("javascript:load_night()");            break;        case R.id.btn_lightmode:            webView.loadUrl("javascript:load_day()");            break;        default:            break;        }    }
Final effect

Full code
 PackageCom.infzm.webview;Importandroid.app.Activity;ImportAndroid.content.Intent;ImportAndroid.net.Uri;ImportAndroid.os.Bundle;ImportAndroid.view.KeyEvent;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.webkit.WebSettings;ImportAndroid.webkit.WebView;ImportAndroid.webkit.WebViewClient;ImportAndroid.widget.Button; Public  class mainactivity extends Activity implements Onclicklistener {    PrivateWebView WebView;PrivateButton nightmodebtn;PrivateButton lightmodebtn;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); WebView = (WebView) This. Findviewbyid (R.id.webview); NIGHTMODEBTN = (Button) This. Findviewbyid (R.id.btn_nightmode); LIGHTMODEBTN = (Button) This. Findviewbyid (R.id.btn_lightmode); Nightmodebtn.setonclicklistener ( This); Lightmodebtn.setonclicklistener ( This);//Webview.loadurl ("http://www.baidu.com");WebSettings settings = Webview.getsettings ();//Set JavaScript availableSettings.setjavascriptenabled (true);//Bind JavaScript interface, can implement call our Android code in JavaScript//Webview.addjavascriptinterface (new Webappinterface (This), "Android");//Webview.setwebviewclient (New Mywebviewclient ());        //Load HTML page in assets directoryWebview.loadurl ("File:///android_asset/01.html"); }/** * for controlling page navigation * @author wwj_748 * */    Private  class mywebviewclient extends webviewclient {        /** * When used to click on a link, the system calls this method * /        @Override         Public Boolean shouldoverrideurlloading(WebView view, String URL) {if(Uri.parse (URL). GetHost (). Equals ("Www.baidu.com")) {//This is my webpage, so do not overwrite, let my webview to load the page                return false; }//Otherwise, this link is not my Site page, so browser is enabled to process URLsIntent Intent =NewIntent (Intent.action_view, Uri.parse (URL)); StartActivity (Intent);return true; }    }@Override     Public Boolean OnKeyDown(intKeyCode, KeyEvent event) {//Check whether the event is returned, if there is a page history        if(KeyCode = = Keyevent.keycode_back && webview.cangoback ()) {Webview.goback ();return true; }//If not a return key or no web browsing history, keep the default        //System behavior (may exit the activity)        return Super. OnKeyDown (KeyCode, event); }@Override     Public void OnClick(View v) {Switch(V.getid ()) { CaseR.id.btn_nightmode:webview.loadurl ("Javascript:load_night ()"); Break; CaseR.id.btn_lightmode:webview.loadurl ("Javascript:load_day ()"); Break;default: Break; }    }}

http://download.csdn.net/detail/wwj_748/8554833

Reprint Please specify: It_xiao Wizard
Blog Address: http://blog.csdn.net/wwj_748
Mobile Development Enthusiast Group: 299402133

Android record 24-webview for daytime/night reading mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.