带进度条的webview,支持网页前进和返回、刷新,返回键goBack等.

来源:互联网 发布:市场调研数据分析方法 编辑:程序博客网 时间:2024/06/01 14:22
转载请注明出处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页面和主布局页面都在上面。

1 0
原创粉丝点击