Android开发-WebView

WebView

  • 加载网页
    1.加载URL(网络或者本地assets文件下的html文件)
    2.加载htmL代码
    3.Native和JavaScripte相互调用

效果图


WebView效果图

WebView layout



    //在某些低版本手机上使用WebView崩溃??  
    

WebViewActivity

public class WebViewActivity extends AppCompatActivity {

    private WebView mWebView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        mWebView = findViewById(R.id.wv);
//        mWebView.loadUrl("file:///android_asset/test.html");

        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.setWebChromeClient(new MyWebChromeClient());
//        mWebView.addJavascriptInterface();
        mWebView.loadUrl("https://m.baidu.com");
    }

    class MyWebChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            setTitle("百度一下");
        }

    }

    class MyWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            // 限制使用内置浏览器
            view.loadUrl(request.getUrl().toString());
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            Log.d("WebView", "onPageStarted...");
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            Log.d("WebView", "onPageFinished...");
//            mWebView.loadUrl("javascript:alert('hello')");
//            mWebView.evaluateJavascript("javascript:alert('hello')", null);
        }
    }

    // 修改点击返回按钮效果
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}

你可能感兴趣的:(Android开发-WebView)