Webview is equivalent to a browser in Android. developed based on WebKit, webview allows you to browse webpage files, and supports CSS JavaScript and HTML
To use webview, you must first configure the following:
1. androidmanifest. "android. permission. internet "for permission. (If you only use local HTML, you do not need to register the permission.) otherwise, the web page not available error may occur.
2. if Javascript is used on the web, JavaScript Execution is required:
JavaCode:
- Webview webv = (webview) findviewbyid (R. Id. webv );
- // Obtain webview from XML
- Webv. getsettings (). setjavascriptenabled (true );
- // Allows JS execution
Copy code
3. If we do not want to create a webview process when using webview for applicationProgramPerform the following settings
Java code:
- Webv. setwebviewclient (New webviewclient (){
- Public Boolean shouldoverrideurlloading (webview view, string URL ){
- View. loadurl (URL );
- // Load the URL on the original process again when you click the hyperlink
- Return true;
- }
- });
Copy code
4. During webview development, the HTML files of the local machine are often loaded as follows:
Java code:
- File: // android_asset/teste.html: The teste.html file under assets.
- File: // index.html file under sdcard/index.html export sdcard
Copy code
5. Call the Java method in Javascript
5.1 bind a current Java object to a JavaScript Object first. Use the following method:
Webv. addjavascriptinterface (this, "something"); // This is the current object and bound to the something of JS. The scope of the main something is global. Once initialized, it can run anywhere
5.2 define the called Java method
Java code:
- Package EOE. Demo;
- Import Android. App. activity;
- Import Android. OS. Bundle;
- Import Android. WebKit. webview;
- Public class sdfsdfsd extends activity {
- /** Called when the activity is first created .*/
- Webview webv;
- @ Override
- Public void oncreate (bundle savedinstancestate ){
- Super. oncreate (savedinstancestate );
- Setcontentview (R. layout. Main );
- Webv = (webview) findviewbyid (R. Id. webv );
- Webv. getsettings (). setjavascriptenabled (true );
- Webv. addjavascriptinterface (this, "something ");
- Webv. loadurl (File: // android_asset/index.html );
- }
- Public void setsmething (string some ){
- System. Out. println ("----------" + some + "---------------");
- }
- }
Copy code
HTML code:
Java code:
- <HTML>
- <Head>
- <Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
- <Title> </title>
- <Script language = "JavaScript" type = "html/text">
- Function dosomething (){
- Document. getelementbyid ("helloweb"). innerhtml = "hellowebview ";
- }
- </SCRIPT>
- </Head>
- <Body onload = "javascript: window. Something. setsmething ('hellowebview')">
- <Div id = "helloweb">
- </Div>
- </Body>
- </Html>
Copy code