帶進度條的webview,支援網頁前進和返回、重新整理,返回鍵goBack等.

來源:互聯網
上載者:User

標籤:

轉載請註明出處http://blog.csdn.net/sinat_25689603/article/details/51917294
本文出自yedongyang的部落格
1.介紹一款很簡單的webview,頭部有進度條,支援網頁前進和返回、重新整理,返回鍵goBack等,可定製性強,漂亮簡潔大方,整合到軟體裡很方便,功能還不複雜。
2.


3.代碼介紹因為有標題頭,所以這裡我是繼承LinearLayout。
public class WebViewLayout extends LinearLayout

初始化添加了頭部和webview,頭部裡包含進度條,設定了幾個自訂屬性,方便調用,如果你需要定製其他的東西,你可以自己加入屬性,比如頭部顏色,進度條顏色,頭部高度,我這裡是寫死的。
@SuppressLint("SetJavaScriptEnabled")    private void init(Context context, AttributeSet attrs) {        setOrientation(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();        //添加頭部        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);        //添加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();//設定標題列    }

標題列退出activity按鈕我是用的回調,在你的activity進行finish,下面是頭部按鈕的調用
/**     * 設定標題列     */    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(WebView 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 void onProgressChanged(WebView view, int newProgress) {            if (newProgress == 100) {                progressbar.setVisibility(GONE);            } else {                if (progressbar.getVisibility() == GONE)                    progressbar.setVisibility(VISIBLE);                progressbar.setProgress(newProgress);            }            super.onProgressChanged(view, newProgress);        }    }

最後是一個返回鍵的監聽,你可以自己進行修改
@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.使用方法布局,共有三個自訂屬性
<?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:orientation="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;//是否根據網頁改變titleprivate boolean isShowIconBack;//是否顯示上一頁下一頁表徵圖private boolean isJavaScriptEnabled;//是否允許JavaScript
我這裡就寫了這三個介面,你需要什麼你加上什麼屬性就行
下面這個是activity裡的調用方法,有三個方法,setTitleText():如果你設定了自動更新標題,這個方法無效。剩下兩個一個是是否顯示頭部,一般用不到,另一個是退出activity的回調調用,記得加上。
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.全部源碼webview_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:layout_height="match_parent"            android:gravity="center"            android:paddingLeft="@dimen/dp12"            android:paddingRight="@dimen/dp12"            android:src="@mipmap/ic_arrow_back_white_24dp"            android:visibility="visible" />        <ImageView            android:id="@+id/title_before"            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_navigate_before_white_24dp"            android:visibility="gone" />        <TextView            android:id="@+id/title_text"            android:layout_width="0dp"            android: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"            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_navigate_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_refresh_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:style/Widget.ProgressBar.Horizontal" /></RelativeLayout>

progressbar的顏色Drawable
<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android" >    <!-- 背景 -->    <item android:id="@android:id/background">        <shape>            <corners android:radius="0dp" />            <solid android:color="@color/AppThemeBackground" />        </shape>    </item>    <!-- 進度條 -->    <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>

自訂屬性放入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
/** * 自訂Webview頁面 * 我的部落格:http://blog.csdn.net/sinat_25689603 * yedongyang * created by ydy on 2016/7/15 9:32 */public class WebViewLayout extends LinearLayout {    private LayoutInflater inflater;    private View titleView;//頭部    private ProgressBar progressbar;//進度條    private WebView webView;//網頁    private ImageView titleLeft;//返回    private ImageView titleBefore;//返回前一個網頁    private TextView titleText;//標題    private ImageView titleNext;//進入下一個網頁    private ImageView titleRight;//重新整理    private boolean isUpdateTitle;//是否根據網頁改變title    private boolean isShowIconBack;//是否顯示上一頁下一頁表徵圖    private boolean isJavaScriptEnabled;//是否允許JavaScript    private int titleHeight;//頭部高度    private WebViewCallBack callBack;//回調    public WebViewLayout(Context context, AttributeSet attrs) {        super(context, attrs);        init(context, attrs);    }    public WebViewLayout(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        init(context, attrs);    }    @SuppressLint("SetJavaScriptEnabled")    private void init(Context context, AttributeSet attrs) {        setOrientation(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();        //添加頭部        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);        //添加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();//設定標題列    }    /**     * 設定標題列     */    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(WebView 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 void onProgressChanged(WebView view, int newProgress) {            if (newProgress == 100) {                progressbar.setVisibility(GONE);            } else {                if (progressbar.getVisibility() == GONE)                    progressbar.setVisibility(VISIBLE);                progressbar.setProgress(newProgress);            }            super.onProgressChanged(view, newProgress);        }    }    /**     * 設定標題列文字,只有在isUpdateTitle為false時有用     */    public void setTitleText(String text){        if(!isUpdateTitle){            titleText.setText(text);        }    }    /**     * 設定標題列文字,只有在isUpdateTitle為false時有用     */    public void setTitleText(int textRes){        if(!isUpdateTitle){            titleText.setText(textRes);        }    }    /**     * 設定標題列是否隱藏     */    public void setTitleVisibility(boolean isVisible){        if(isVisible){            titleView.setVisibility(View.VISIBLE);        }else{            titleView.setVisibility(View.GONE);        }    }    /**     * 載入網頁     * 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.canGoBack()){                webView.goBack();                return true;            }        }        return super.dispatchKeyEvent(event);    }}

至於Activity頁面和主布局頁面都在上面。

帶進度條的webview,支援網頁前進和返回、重新整理,返回鍵goBack等.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.