WebView with progress bar, support page forward and return, refresh, return key GoBack and so on.

Source: Internet
Author: User

Reprint please specify the source http://blog.csdn.net/sinat_25689603/article/details/51917294
This article is from Yedongyang's blog
1. Introductiona very simple webview, the head has a progress bar, support page forward and return, refresh, return key GoBack, etc., can be customized strong, beautiful simple and generous, integrated into the software is very convenient, the function is not complex.
2.


3. Code Introductionbecause there are header headers, so here I am inheriting linearlayout.
public class Webviewlayout extends LinearLayout

initialization added head and WebView, the head contains a progress bar, set a few custom properties, convenient to call, if you need to customize other things, you can add their own properties, such as the head color, progress bar color, head height, I am writing dead here.
@SuppressLint ("setjavascriptenabled") private void init (context context, AttributeSet attrs) {setorientation (Li        nearlayout.vertical);        TypedArray TypedArray = context.obtainstyledattributes (Attrs, r.styleable.webviewlayout);        Isupdatetitle = Typedarray.getboolean (R.styleable.webviewlayout_isupdatetitle, false);        Isshowiconback = Typedarray.getboolean (R.styleable.webviewlayout_isshowiconback, false);        isjavascriptenabled = Typedarray.getboolean (r.styleable.webviewlayout_isjavascriptenabled, false);        Typedarray.recycle ();        Add Head Inflater = (layoutinflater) context.getsystemservice (Context.layout_inflater_service);        Titleview = inflater.inflate (R.layout.webview_title_bar, NULL, FALSE);        Titleview.setlayoutparams (New Relativelayout.layoutparams (Layoutparams.match_parent, ToolsUtil.dip2px (48)));        Titleleft = (ImageView) Titleview.findviewbyid (r.id.title_left); Titlebefore = (ImageView) Titleview.findviewbyid (r.id. Title_before);        TitleText = (TextView) Titleview.findviewbyid (R.id.title_text);        Titlenext = (ImageView) Titleview.findviewbyid (R.id.title_next);        Titleright = (ImageView) Titleview.findviewbyid (r.id.title_right);        ProgressBar = (ProgressBar) Titleview.findviewbyid (r.id.progress);        AddView (Titleview);        Add WebView WebView = new WebView (context);        Webview.setlayoutparams (New Linearlayout.layoutparams (Layoutparams.match_parent, layoutparams.match_parent));        Webview.getsettings (). setjavascriptenabled (isjavascriptenabled);        Webview.setwebviewclient (New Webviewclient ());        Webview.setwebchromeclient (New Webchromeclient ());        AddView (WebView); Settitleview ();//set title bar}

Title bar exit Activity button I am using the callback, in your activity to finish, below is the call of the head button
/**     * Set title bar */    private void Settitleview () {        Titleleft.setonclicklistener (new View.onclicklistener ( {            @Override public            void OnClick (View v) {                if (callBack! = null) {Callback.backonclick ();}            }        );        Titlebefore.setonclicklistener (New View.onclicklistener () {            @Override public            void OnClick (View v) {                Webview.goback ();            }        });        Titlenext.setonclicklistener (New View.onclicklistener () {            @Override public            void OnClick (View v) {                Webview.goforward ();            }        });        Titleright.setonclicklistener (New View.onclicklistener () {            @Override public            void OnClick (View v) {                Webview.reload ();}}        );    }

The following is a way to set the progress bar and set the header back up and go to the next page.
public class Webviewclient extends android.webkit.webviewclient{@Override public void onpagefinished (Webvie            W view, String URL) {if (isupdatetitle) Titletext.settext (View.gettitle ());            Boolean back = View.cangoback ();            Boolean forward = View.cangoforward (); if (back | | forward) {titlebefore.setvisibility-isshowiconback && back?                View.VISIBLE:View.GONE); Titlenext.setvisibility (Isshowiconback && forward?            View.VISIBLE:View.GONE);                } else {titlebefore.setvisibility (view.gone);            Titlenext.setvisibility (View.gone); }}} public class Webchromeclient extends Android.webkit.WebChromeClient {@Override public vo ID onprogresschanged (WebView view, int newprogress) {if (newprogress = =) {Progressbar.setv            Isibility (GONE); } else {if (PROGRESSBAr.getvisibility () = = GONE) progressbar.setvisibility (VISIBLE);            Progressbar.setprogress (newprogress);        } super.onprogresschanged (view, newprogress); }    }

Finally, a back-button listener, you can modify it yourself
@Override Public    Boolean dispatchkeyevent (KeyEvent event) {        if (event.getkeycode () = = Keyevent.keycode_back && event.getaction () = = Keyevent.action_down && event.getrepeatcount () = = 0) {            if ( Webview.cangoback ()) {                webview.goback ();                return true;            }        }        Return Super.dispatchkeyevent (event);    }
4. How to uselayouts, total three custom properties
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    xmlns:tools=" Http://schemas.android.com/tools "    android:layout_width=" Match_parent    " android:layout_height= "Match_parent"    xmlns:app= "Http://schemas.android.com/apk/res-auto"    android:o rientation= "vertical"    tools:context= ". UI. Usinghelpactivity ">    <com.zzsoft.app.widget.webviewlayout        android:id=" @+id/webviewlayout "        Android:layout_width= "Match_parent"        android:layout_height= "match_parent"        app:isupdatetitle= "true"        app:isshowiconback= "true"        app:isjavascriptenabled= "true"/></linearlayout>

Private Boolean isupdatetitle;//whether the Titleprivate Boolean isshowiconback;//is changed according to the Web page if the previous page next icon is displayed private Boolean isjavascriptenabled;//whether JavaScript is allowed
I wrote these three interfaces here, you need what you want to add to the property.
here is the call method in the activity, there are three methods, Settitletext (): If you set the automatic update title, this method is invalid. The remaining two one is whether to show the head, generally do not use, and the other is to exit the activity callback call, remember to add.
private void Initview () {        webviewlayout.settitletext (r.string.my_using_help);        Webviewlayout.settitlevisibility (true);        Webviewlayout.setwebviewcallback (New Webviewlayout.webviewcallback () {            @Override public            void Backonclick () {                activity.this.finish ();            }        });        Webviewlayout.loadurl ("http://www.baidu.com");    }
5. All source codeWebview_title_bar.xml
<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/    Android "android:id=" @+id/title_layout "android:layout_width=" match_parent "android:layout_height=" @dimen/dp48 " android:background= "@color/appthemebackground" android:orientation= "vertical" > <linearlayout android:        Layout_width= "Match_parent" android:layout_height= "match_parent" android:orientation= "Horizontal" > <imageview android:id= "@+id/title_left" android:layout_width= "Wrap_content" android:l ayout_height= "match_parent" android:gravity= "center" android:paddingleft= "@dimen/dp12" an droid:paddingright= "@dimen/dp12" android:src= "@mipmap/ic_arrow_back_white_24dp" android:visibility= " Visible "/> <imageview android:id=" @+id/title_before "android:layout_width=" Wrap_conten T "Android:layout_height= "match_parent" android:gravity= "center" android:paddingleft= "@dimen/dp12" Android:padd  ingright= "@dimen/dp12" android:src= "@mipmap/ic_navigate_before_white_24dp" android:visibility= "Gone" /> <textview android:id= "@+id/title_text" android:layout_width= "0DP" Androi d:layout_height= "Match_parent" android:layout_weight= "1" android:gravity= "Center" Android            : Singleline= "true" android:text= "@string/app_name" android:textcolor= "@color/appthemetextcolor" Android:textsize= "@dimen/sp18"/> <imageview android:id= "@+id/title_next" Androi            D:layout_width= "Wrap_content" android:layout_height= "match_parent" android:gravity= "center" android:paddingleft= "@dimen/dp12" android:paddingright= "@dimen/dp12" android:src= "@mipmap/ic_navi   GATE_NEXT_WHITE_24DP "         android:visibility= "Gone"/> <imageview android:id= "@+id/title_right" Android:            Layout_width= "Wrap_content" android:layout_height= "match_parent" android:gravity= "center" android:paddingleft= "@dimen/dp12" android:paddingright= "@dimen/dp12" android:src= "@mipmap/ic_refres H_WHITE_24DP "android:visibility=" visible "/> </LinearLayout> <progressbar android:id= "@+id/progress" android:layout_width= "match_parent" android:layout_height= "@dimen/dp4" android:layout _alignparentbottom= "true" android:progressdrawable= "@drawable/webviewlayout_progressbar" style= "@android: sty Le/widget.progressbar.horizontal "/></relativelayout>

The color of ProgressBar drawable
<?xml version= "1.0" encoding= "Utf-8"? ><layer-list xmlns:android= "http://schemas.android.com/apk/res/ Android >    <!--background--    <item android:id= "@android: Id/background" >        <shape>            <corners android:radius= "0DP"/>            <solid android:color= "@color/appthemebackground"/>        </ shape>    </item>    <!--progress Bar--    <item android:id= "@android: id/progress" >        < clip>            <shape>                <corners android:radius= "0DP"/>                <solid android:color= "@color/ Webview_progress "/>            </shape>        </clip>    </item></layer-list>
<color name= "Appthemebackground" > #1E8BF2 </color><color name= "webview_progress" > #A7CEF2 </ Color>

Custom attributes put inside Attrs.xml
<declare-styleable name= "Webviewlayout" >     <attr name= "Isupdatetitle" format= "boolean"/>     < attr name= "Isshowiconback" format= "boolean"/> <attr name=     "isjavascriptenabled" format= "boolean"/>< /declare-styleable>>

Webviewlayout.java
/** * Custom WebView page * My blog: http://blog.csdn.net/sinat_25689603 * Yedongyang * created by ydy on 2016/7/15 9:32 */public CLA    SS Webviewlayout extends LinearLayout {private Layoutinflater inflater; Private View titleview;//Head private ProgressBar progressbar;//progress bar Private WebView webview;//Web page Private ImageView titleleft;//return private ImageView titlebefore;//return to previous page private TextView titletext;//title private ImageView Titlenex t;//Enter the next page private ImageView titleright;//Refresh private Boolean isupdatetitle;//whether to change the title private Boolean Issho according to the page wiconback;//whether to display the previous page next icon private Boolean isjavascriptenabled;//whether to allow JavaScript private int titleheight;//Head height priv Ate Webviewcallback callback;//Callback public webviewlayout (context context, AttributeSet Attrs) {Super (context, ATT        RS);    Init (context, attrs); } public Webviewlayout (context context, AttributeSet attrs, int defstyleattr) {Super (context, Attrs, defstyleat        TR); Init (Context, attrs); } @SuppressLint ("setjavascriptenabled") private void init (context context, AttributeSet attrs) {Setorientati        On (linearlayout.vertical);        TypedArray TypedArray = context.obtainstyledattributes (Attrs, r.styleable.webviewlayout);        Isupdatetitle = Typedarray.getboolean (R.styleable.webviewlayout_isupdatetitle, false);        Isshowiconback = Typedarray.getboolean (R.styleable.webviewlayout_isshowiconback, false);        isjavascriptenabled = Typedarray.getboolean (r.styleable.webviewlayout_isjavascriptenabled, false);        Typedarray.recycle ();        Add Head Inflater = (layoutinflater) context.getsystemservice (Context.layout_inflater_service);        Titleview = inflater.inflate (R.layout.webview_title_bar, NULL, FALSE);        Titleview.setlayoutparams (New Relativelayout.layoutparams (Layoutparams.match_parent, ToolsUtil.dip2px (48)));        Titleleft = (ImageView) Titleview.findviewbyid (r.id.title_left); Titlebefore = (ImageView) titleview.findvIewbyid (R.id.title_before);        TitleText = (TextView) Titleview.findviewbyid (R.id.title_text);        Titlenext = (ImageView) Titleview.findviewbyid (R.id.title_next);        Titleright = (ImageView) Titleview.findviewbyid (r.id.title_right);        ProgressBar = (ProgressBar) Titleview.findviewbyid (r.id.progress);        AddView (Titleview);        Add WebView WebView = new WebView (context);        Webview.setlayoutparams (New Linearlayout.layoutparams (Layoutparams.match_parent, layoutparams.match_parent));        Webview.getsettings (). setjavascriptenabled (isjavascriptenabled);        Webview.setwebviewclient (New Webviewclient ());        Webview.setwebchromeclient (New Webchromeclient ());        AddView (WebView); Settitleview ();//Set title bar}/** * Set title bar */private void Settitleview () {Titleleft.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {if (CallBack! = NULL) {Callback.backOnclick ();}        }        });                Titlebefore.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {            Webview.goback ();        }        });                Titlenext.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {            Webview.goforward ();        }        });                Titleright.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {            Webview.reload ();    }        }); } public class Webviewclient extends android.webkit.webviewclient{@Override public void onpagefinished (W            Ebview view, String URL) {if (isupdatetitle) Titletext.settext (View.gettitle ());            Boolean back = View.cangoback ();            Boolean forward = View.cangoforward (); if (back | | forward) {titlebefore.setvisibility (isshOwiconback && back?                View.VISIBLE:View.GONE); Titlenext.setvisibility (Isshowiconback && forward?            View.VISIBLE:View.GONE);                } else {titlebefore.setvisibility (view.gone);            Titlenext.setvisibility (View.gone); }}} public class Webchromeclient extends Android.webkit.WebChromeClient {@Override public vo ID onprogresschanged (WebView view, int newprogress) {if (newprogress = =) {Progressbar.setv            Isibility (GONE);                } else {if (progressbar.getvisibility () = = GONE) progressbar.setvisibility (VISIBLE);            Progressbar.setprogress (newprogress);        } super.onprogresschanged (view, newprogress); }}/** * Set title bar text, only useful when Isupdatetitle is false */public void Settitletext (String text) {if (!isupdate        Title) {titletext.settext (text); }    }    /**    * Set title bar text, only useful when Isupdatetitle is false */public void settitletext (int textres) {if (!isupdatetitle) {        Titletext.settext (Textres);            }}/** * Sets whether the title bar is hidden */public void settitlevisibility (Boolean isVisible) {if (isVisible) {        Titleview.setvisibility (view.visible);        }else{titleview.setvisibility (View.gone); }}/** * Load page * created by ydy on 2016/7/15 10:14 */public void Loadurl (String url) {WebView    . Loadurl (URL);    } public void Setwebviewcallback (Webviewcallback callBack) {this.callback = CallBack;    } public interface webviewcallback{void Backonclick (); } @Override public boolean dispatchkeyevent (KeyEvent event) {if (event.getkeycode () = = Keyevent.keycode_back && event.getaction () = = Keyevent.action_down && event.getrepeatcount () = = 0) {if (Webview.cangob               ACK ()) {webview.goback (); return true;    }} return Super.dispatchkeyevent (event); }}

As for the activity page and the main layout page are above.

WebView with progress bar, support page forward and return, refresh, return key GoBack and so on.

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.