Webview application developed for Android

Source: Internet
Author: User

Use of webview in Android Development

The android network has powerful functions. The webview component can directly load webpages and treat them as a browser. To implement this function, follow these steps:

1. Declare webview in the layout File

2. instantiate webview in Activity

3. Call the webview loadurl () method to load the specified URL webpage.

4. To enable webview to respond to the hyperlink function, call the setwebviewclient () method and set the webview Client

5. If the accessed page contains JavaScript, webview must be set to support JavaScript. Webview. getsettings (). setjavascriptenabled (true );

6. To enable webview to support the rollback function, override the onkeydown () method.

7. Be sure to add the Internet access permission to the androidmanifest. xml file. Otherwise, it cannot be displayed.

<Uses-Permission Android: Name = "android. Permission. Internet"/>

The following describes the use of webview in detail through a column. First, let's take a look at the running of this project:


Figure (1) figure (2)


Figure (3) figure (4)

Figure (5)

Figure (1): the interface displayed first when the project is running. On this page, we load an HTML webpage.

Figure (2): The alert dialog box appears when you click the first submit button.

Figure 3: A confirm dialog box is displayed when you click the second submit button.

Figure (4): the prompt dialog box appears when you click the third submit button.

Figure 5: Baidu homepage displayed when we enter the Baidu website in edittext.

The following describes the entire process of project development:

1. Create an android project named webviewtest.

2. Create an HTML page named dialog.html and put it in the Assets Directory. The Code is as follows:

<HTML xmlns = "http://www.w3.org/1999/xhtml"> 

On this page, three buttons are declared, which are used for JavaScript scripts to display three different dialogs.
3. Create a layout file prom_dialog.xml under the layout directory to display the dialog box. The Code is as follows:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:gravity="center_horizontal"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    >    <TextView android:id="@+id/TextView_PROM"    android:layout_width="fill_parent"android:layout_height="wrap_content"/>    <EditText android:id="@+id/EditText_PROM"android:layout_width="fill_parent"android:layout_height="wrap_content"android:selectAllOnFocus="true"android:scrollHorizontally="true"/></LinearLayout>

A textview and an edittext are declared in the layout file. The layout file is used in the third dialog box.

4. Modify the main. xml file of the main layout. The specific content is as follows:

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Orientation = "vertical" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent"> <linearlayout Android: orientation = "horizontal" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: animationcache = "true" Android: layout_weight = "9"> <edittext Android: id = "@ + ID/edittext01" Android: layout_width = "wrap_content" Android: layout_weight = "9" Android: layout_height = "wrap_content" Android: TEXT = "Enter the URL"/> <button Android: Id = "@ + ID/button01" Android: layout_width = "wrap_content" Android: layout_weight = "1" Android: layout_height = "wrap_content" Android: text = ""/> </linearlayout> <webview Android: Id = "@ + ID/webview01" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: layout_weight = "1"/> </linearlayout>

5. Modify the main program file to display various operations. The specific operations are annotated and will not be discussed here. The Code is as follows:

Public class activity01 extends activity {private final string debug_tag = "activity01"; private buttonmbutton; private edittextmedittext; private webviewmwebview; string url = "file: // android_asset/dialog.html "; public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); mbutton = (button) findviewbyid (R. id. button01); medittext = (edittext) findviewbyid (R. id. edittext01); mwebview = (webview) findviewbyid (R. id. webview01); // supports the Javascript script websettings = mwebview. getsettings (); websettings. setjavascriptenabled (true); // sets websettings for file access. setallowfileaccess (true); // The settings support scaling websettings. setbuiltinzoomcontrols (true); mwebview. loadurl (URL); // sets webviewclientmwebview. setwebviewclient (New webviewclient () {public Boolean shouldoverrideurlloading (webview view, string URL) {view. loadurl (URL); Return true ;}@ overridepublic void onpagefinished (webview view, string URL) {super. onpagefinished (view, URL) ;}@ overridepublic void onpagestarted (webview view, string URL, bitmap favicon) {super. onpagestarted (view, URL, favicon) ;}}); // sets webchromeclientmwebview. setwebchromeclient (New webchromeclient () {@ override // process alertpublic Boolean onjsalert (webview view, string URL, string message, final jsresult result) in Javascript) {// construct a builder to display the dialog box builder = new Builder (activity01.this); builder. settitle ("prompt dialog box"); builder. setmessage (Message); builder. setpositivebutton (Android. r. string. OK, new alertdialog. onclicklistener () {public void onclick (dialoginterface Diener, int which) {// Click OK to continue the operation result on the webpage. confirm () ;}}); builder. setcancelable (false); builder. create (); builder. show (); Return true ;}; // process confirmpublic Boolean onjsconfirm in JavaScript (webview view, string URL, string message, final jsresult result) {Builder = new Builder (activity01.this); builder. settitle ("selected dialog box"); builder. setmessage (Message); builder. setpositivebutton (Android. r. string. OK, new alertdialog. onclicklistener () {public void onclick (dialoginterface dialog, int which) {result. confirm () ;}}); builder. setnegativebutton (Android. r. string. cancel, new dialoginterface. onclicklistener () {public void onclick (dialoginterface dialog, int which) {result. cancel () ;}}); builder. setcancelable (false); builder. create (); builder. show (); Return true ;}; // process the prompt in Javascript // message as the prompt in the dialog box on the webpage // when defaultvalue is not input, the content displayed by default is public Boolean onjsprompt (webview view, string URL, string message, string defaultvalue, final jspromptresult result) {// customize an input-containing dialog box consisting of textview and edittext: Final layoutinflater factory = layoutinflater. from (activity01.this); final view dialogview = factory. inflate (R. layout. prom_dialog, null); // sets the prompt information (textview) dialogview in the textview corresponding to the webpage. findviewbyid (R. id. textview_prom )). settext (Message); // set the input box (edittext) dialogview In the webpage corresponding to edittext. findviewbyid (R. id. edittext_prom )). settext (defaultvalue); Builder = new Builder (activity01.this); builder. settitle ("dialog box with input"); builder. setview (dialogview); builder. setpositivebutton (Android. r. string. OK, new alertdialog. onclicklistener () {public void onclick (dialoginterface Diener, int which) {// Click OK to obtain the input value and send it to the webpage for processing string value = (edittext) dialogview. findviewbyid (R. id. edittext_prom )). gettext (). tostring (); result. confirm (value) ;}}); builder. setnegativebutton (Android. r. string. cancel, new dialoginterface. onclicklistener () {public void onclick (dialoginterface dialog, int which) {result. cancel () ;}}); builder. setoncancellistener (New dialoginterface. oncancellistener () {public void oncancel (dialoginterface DIALOG) {result. cancel () ;}}); builder. show (); Return true ;}; // set the progress bar public void onprogresschanged (webview view, int newprogress) {activity01.this. getwindow (). setfeatureint (window. feature_progress, newprogress * 100); super. onprogresschanged (view, newprogress);} // set the application title titlepublic void onreceivedtitle (webview view, String title) {activity01.this. settitle (title); super. onreceivedtitle (view, title) ;}}); // listens for mbutton connection button events. setonclicklistener (New onclicklistener () {public void onclick (view v) {try {// get the content we entered in the edit box string url = medittext. gettext (). tostring (); // determines whether the input content is URL if (urlutil. isnetworkurl (URL) {// load the URL mwebview. loadurl (URL);} else {medittext. settext ("Enter URL error, please enter again") ;}} catch (exception e) {log. E (debug_tag, E. tostring () ;}}) ;}public Boolean onkeydown (INT keycode, keyevent event) {If (keycode = keyevent. keycode_back) & mwebview. cangoback () {// return to the previous page of mwebview. goback (); Return true;} return Super. onkeydown (keycode, event );}}

6. Do not forget to add "android. Permission. Internet" to androidmanifest. xml. Otherwise, the web page not available error may occur.

7. The project is developed now. The above results will be obtained after execution.

Note the following knowledge points:

1) To allow webview to load assets from the APK file, the android SDK provides a schema prefixed with "file: // android_asset /". When webview encounters such a schema, it finds the content in the Assets Directory of the current package. Above "file: // android_asset/dialog.html"

2) Here we add three different dialog box prompts for dialog. in the program, we also use three different JavaScript scripts to process these three dialog boxes. Avoid using different functions in different dialogs for corresponding processing.

 

Finally, we will summarize:

1. add permissions: The permission "android. Permission. Internet" must be used in androidmanifest. xml. Otherwise, the web page not available error may occur.
2. Generate a webview component in the activity: webview = new webview (this );
3. Set Basic webview information:
If the accessed page contains JavaScript, webview must be set to support JavaScript.
Webview. getsettings (). setjavascriptenabled (true );
Touch focus Function
Requestfocus ();
Cancel scroll bar
This. setscrollbarstyle (scrollbars_outside_overlay );
4. Set the web page to be displayed in wevview:
For Internet: webview. loadurl ("http://www.google.com ");

Local file: webview. loadurl ("file: // android_asset/xx.html"); local files are stored in the assets file.
5. If you want to click the link, you can handle it by yourself, instead of clicking the link in the browser of the new Android system.
Add an event listening object (webviewclient) to webview)

And rewrite some of the methods.
Shouldoverrideurlloading: Response to the hyperlink button on the webpage.
When you press a connection, webviewclient will call this method and pass the parameter: URL

Onloadresource
Onpagestart
Onpagefinish
Onreceiveerror
Onreceivedhttpauthrequest

6. If you use the webview link to view many pages without any processing, click the system "back" key and the entire browser will call finish () to end itself, if you want to roll back the web page instead of exiting the browser, you need to process and consume the back event in the current activity.
Override the onkeydown (INT keycoder, keyevent event) method of the activity class.

  1. Public Boolean onkeydown (INT keycoder, keyevent event ){
  2. If (webview. cangoback () & keycoder = keyevent. keycode_back ){
  3. Webview. Goback (); // Goback () indicates that the previous page of webview is returned.
  4. Return true;
  5. }
  6. Return false;
  7. }

 

 

Related Article

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.