一个标准的WebView示例

2022-01-12 15:28:58 浏览数 (1)

代码语言:javascript复制
xml
代码语言:javascript复制
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <android.support.v7.widget.Toolbar
            android:id="@ id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:theme="@style/ThemeOverlay.AppCompat.Light" />
    </android.support.design.widget.AppBarLayout>
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <WebView
            android:id="@ id/web_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
        <ProgressBar
            android:id="@ id/progress_bar"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_gravity="center"
            android:visibility="gone" />
    </FrameLayout>
</LinearLayout>
代码语言:javascript复制
MainActivity 
代码语言:javascript复制
public class MainActivity extends AppCompatActivity {
    private WebView mWebView;
    private ProgressBar mProgressbar;
    private Toolbar mToolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initAppBar();//初始化Toolbar
        initWebView();//初始化WebView
        initWebSettings();//初始化WebSettings
        initWebViewClient();//初始化WebViewClient
        initWebChromeClient();//初始化WebChromeClient
    }
    private void initAppBar() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setTitle("载入中..");
        mToolbar.setTitleTextColor(getResources().getColor(R.color.colorWhite));
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    }
    private void initWebView() {
        mWebView = (WebView) findViewById(R.id.web_view);
        mProgressbar = (ProgressBar) findViewById(R.id.progress_bar);
        String url = "https://www.google.com";
        mWebView.loadUrl(url);
    }
    private void initWebSettings() {
        WebSettings settings = mWebView.getSettings();
        //支持获取手势焦点
        mWebView.requestFocusFromTouch();
        //支持JS
        settings.setJavaScriptEnabled(true);
        //支持插件
        settings.setPluginState(WebSettings.PluginState.ON);
        //设置适应屏幕
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        //支持缩放
        settings.setSupportZoom(false);
        //隐藏原生的缩放控件
        settings.setDisplayZoomControls(false);
        //支持内容重新布局
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.supportMultipleWindows();
        settings.setSupportMultipleWindows(true);
        //设置缓存模式
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setAppCacheEnabled(true);
        settings.setAppCachePath(mWebView.getContext().getCacheDir().getAbsolutePath());
        //设置可访问文件
        settings.setAllowFileAccess(true);
        //当webview调用requestFocus时为webview设置节点
        settings.setNeedInitialFocus(true);
        //支持自动加载图片
        if (Build.VERSION.SDK_INT >= 19) {
            settings.setLoadsImagesAutomatically(true);
        } else {
            settings.setLoadsImagesAutomatically(false);
        }
        settings.setNeedInitialFocus(true);
        //设置编码格式
        settings.setDefaultTextEncodingName("UTF-8");
    }
    private void initWebViewClient() {
        mWebView.setWebViewClient(new WebViewClient() {
            //页面开始加载时
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                mProgressbar.setVisibility(View.VISIBLE);
            }
            //页面完成加载时
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                mProgressbar.setVisibility(View.GONE);
            }
            //是否在WebView内加载新页面,可以在这里判断URL做相应操作
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                view.loadUrl(request.toString());
                return true;
            }
            //网络错误时回调的方法
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                /**
                 * 在这里写网络错误时的逻辑,比如显示一个错误页面
                 *
                 *
                 * */
            }
            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
            }
        });
    }
    private void initWebChromeClient() {
        mWebView.setWebChromeClient(new WebChromeClient() {
            private Bitmap mDefaultVideoPoster;//默认的视频展示图
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                setToolbarTitle(title);
            }
            @Override
            public Bitmap getDefaultVideoPoster() {
                if (mDefaultVideoPoster == null) {
                    mDefaultVideoPoster = BitmapFactory.decodeResource(
                            getResources(), R.drawable.video_default
                    );
                    return mDefaultVideoPoster;
                }
                return super.getDefaultVideoPoster();
            }
        });
    }
    /**
     * 设置Toolbar标题
     *
     * @param title
     */
    private void setToolbarTitle(final String title) {
        Log.d("setToolbarTitle", " WebDetailActivity "   title);
        if (mToolbar != null) {
            mToolbar.post(new Runnable() {
                @Override
                public void run() {
                    mToolbar.setTitle(TextUtils.isEmpty(title) ? getString(R.string.loading) : title);
                }
            });
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.page_up:
                Toast.makeText(getApplicationContext(), "页面向上", Toast.LENGTH_SHORT).show();
                mWebView.pageUp(true);
                break;
            case R.id.page_down:
                Toast.makeText(getApplicationContext(), "页面向下", Toast.LENGTH_SHORT).show();
                mWebView.pageDown(true);
                break;
            case R.id.refresh:
                Toast.makeText(getApplicationContext(), "刷新~", Toast.LENGTH_SHORT).show();
                mWebView.reload();
            default:
                return super.onOptionsItemSelected(item);
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //如果按下的是回退键且历史记录里确实还有页面
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        } else {
            Toast.makeText(getApplicationContext(), "OVER!", Toast.LENGTH_LONG).show();
        }
        return super.onKeyDown(keyCode, event);
    }
}

本地调用h5

代码语言:javascript复制
  contentWebView.loadUrl("javascript:javacalljs()");//无参
  contentWebView.loadUrl("javascript:javacalljswith("   "'http://blog.csdn.net/Leejizhou'"   ")");//有参

h5调本地

代码语言:javascript复制
本地方法加@JavascriptInterface
contentWebView.getSettings().setJavaScriptEnabled(true);
//第一个参数是需要js调用的方法所在的地方
contentWebView.addJavascriptInterface(MainActivity.this,"android");
<input type="button"  value="点击调用java代码" onclick="window.android.startFunction()" />

0 人点赞