封装webview

来源:互联网 发布:手机扫描ip软件 编辑:程序博客网 时间:2024/06/05 16:25

最近项目使用的webview比较多,记录一下

public class StrengthenWebView extends RelativeLayout {    private String htmlPath = "";           //网页存放目录    private String jsonData = "";           //json数据字符串    private CallBackWebView contentWebView;    private Context context;    public boolean isViewLoaded = false;    private boolean isHtmlLoaded = false;    private int finishTime = 0;    private WebViewCallBack callBack;    private OnHeightChangeListener onHeightChangeListener;    public StrengthenWebView(Context context, AttributeSet attrs) {        super(context, attrs);        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.StrengthenWebView);        htmlPath = typedArray.getString(R.styleable.StrengthenWebView_htmlPath);        initView(context);    }    public StrengthenWebView(Context context, String htmlPath) {        super(context);        this.htmlPath = htmlPath;        initView(context);    }    protected View initView(Context context) {        this.context = context;        View rootView = View.inflate(context,R.layout.view_strength_web_view, this);        contentWebView = (CallBackWebView) rootView.findViewById(R.id.wv_strengthen);//        WebViewUtils.setWebView(contentWebView);        contentWebView.setWebViewClient(new WebViewClient(){            @Override            public void onPageFinished(WebView view, String url) {                super.onPageFinished(view, url);                isHtmlLoaded = true;                if (callBack!=null){                    callBack.onPageFinish();                }                finishTime++;//                Logger.e("StrengthenWebView #########--------------########## onPageFinished "+isHtmlLoaded);//                if (finishTime==1){//                    isHtmlLoaded = true;//                }            }            @Override            public boolean shouldOverrideUrlLoading(WebView view, String url) {                view.loadUrl(url);                return true;            }            @Override            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {                super.onReceivedError(view, request, error);                Logger.e("StrengthenWebView -----Error--"+request.toString()+" "+error.toString());            }        });        contentWebView.loadUrl(htmlPath);        JsonContacts jsonContacts = new JsonContacts();        contentWebView.addJavascriptInterface(jsonContacts, "jsonContacts");        contentWebView.addJavascriptInterface(new SetHeight(), "setHeight");        return rootView;    }    public void loadJson(){        int index = htmlPath.lastIndexOf("/");        String path =htmlPath.substring(index, htmlPath.length());        Logger.e("Strengthen Webview ------------ loadJson()"+path);        contentWebView.evaluateJavascript("loadJson()", new ValueCallback<String>() {            @Override            public void onReceiveValue(String value) {                if (value!=null){//                    isViewLoaded = true;                    JsonReader reader = new JsonReader(new StringReader(value));                    reader.setLenient(true);                    try {                        if(reader.peek() != JsonToken.NULL) {                            if(reader.peek() == JsonToken.STRING) {                                String msg = reader.nextString();                                if(msg != null) {//                                    Toast.makeText(context.getApplicationContext(),//                                            msg, Toast.LENGTH_LONG).show();                                    Logger.e("onReceiveValue -------- "+value+" "+msg);                                }                            }                        }                    } catch (IOException e) {                        Log.e("TAG", "MainActivity: IOException", e);                    } finally {                        try {                            reader.close();                        } catch (IOException e) {                            // NOOP                        }                    }                }            }        });    }    public void setJsonData(String jsonData) {        this.jsonData = jsonData;    }    public String getJsonData() {        return jsonData;    }    public String getHtmlPath() {        return htmlPath;    }    public void setHtmlPath(String htmlPath) {        //htmlPath基本格式 "file:///android_asset/show.html"        this.htmlPath = htmlPath;        contentWebView.loadUrl(htmlPath);    }    public WebView getContentWebView() {        return contentWebView;    }    public void refresh(){        contentWebView.reload();    }    class SetHeight {        private int realHeight;        @JavascriptInterface        public void setViewHeight(final String height) {            Logger.e("Height is ------------ "+height+" "+contentWebView.getLayoutParams().height);//            final int realHeight = DensityUtil.px2dip(getContext(), Float.parseFloat(height));            realHeight = Integer.parseInt(height);            if (onHeightChangeListener!=null){                onHeightChangeListener.onViewHeightChanged(realHeight);            }            Activity activity = (Activity) context;            activity.runOnUiThread(new Runnable() {                @Override                public void run() {                    ViewGroup.LayoutParams layoutParams = contentWebView.getLayoutParams();                    layoutParams.height = realHeight;                    contentWebView.setLayoutParams(layoutParams);                }            });        }        public int getRealHeight() {            return realHeight;        }        public void setRealHeight(int realHeight) {            this.realHeight = realHeight;        }    }    class JsonContacts implements NativeAndJsContacts {        @Override        @JavascriptInterface        public String getJsonData() {//            Logger.e("StrengthenWebView() getJsonData ---------"+jsonData);            if (!jsonData.equals("")){                String json = jsonData;                return json;            }else {                return null;            }        }        @JavascriptInterface        public String getUrl(){            return CommonParams.BASE_URL;        }        @JavascriptInterface        public String getToken(){            return MyApplication.userToken;        }        @JavascriptInterface        public String getLanguage(){            return MyApplication.language;        }    }    public boolean isHtmlLoaded() {//        isHtmlLoaded = contentWebView.isLoadSuccess();        return isHtmlLoaded;    }    public interface WebViewCallBack{        void onPageFinish();    }    public WebViewCallBack getCallBack() {        return callBack;    }    public void setCallBack(WebViewCallBack callBack) {        this.callBack = callBack;    }    public interface OnHeightChangeListener {        //方法a        public void onViewHeightChanged(int height);    }    //方法b,以定义的接口作为参数    public void setOnHeightChangeListener(OnHeightChangeListener onHeightChangeListener) {        this.onHeightChangeListener = onHeightChangeListener;    }}
自定义属性
    <declare-styleable name="StrengthenWebView">        <attr name="htmlPath" format="string" />    </declare-styleable>
布局文件
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <com.lnsoft.fcis.android.CallBackWebView        android:id="@+id/wv_strengthen"        android:layout_width="match_parent"        android:layout_height="match_parent"/></RelativeLayout>

其中CallBackWebView
public class CallBackWebView extends WebView {    private boolean isLoadSuccess = false;    private LoadedCallBack callBack;    public CallBackWebView(Context context) {        super(context);    }    public CallBackWebView(Context context, AttributeSet attrs) {        super(context, attrs);    }    public CallBackWebView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    public CallBackWebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {        super(context, attrs, defStyleAttr, defStyleRes);    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        isLoadSuccess = true;        if (callBack!=null){            callBack.onLoaded();        }//        Logger.e("CallBackWebView ------------- isLoadSuccess="+isLoadSuccess);    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        invalidate();        super.onMeasure(widthMeasureSpec, heightMeasureSpec);    }    public boolean isLoadSuccess() {        return isLoadSuccess;    }    interface LoadedCallBack {        public void onLoaded();    }    public void setCallBack(LoadedCallBack callBack) {        this.callBack = callBack;    }}




0 0
原创粉丝点击