Android--WebView的使用

这里只是单纯的一个webview的简单使用。

布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MyJNI">
    
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="加载网页"
        android:onClick="loading"/>
    <WebView
        android:id="@+id/wv_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

java

public class MyJNI extends AppCompatActivity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_jni);

        webView=(WebView)findViewById(R.id.wv_main);
    }

    public void loading(View view){

        try {
            //加载本地的html页面
            //将html页面放到assets目录下
//            webView.loadUrl("file:///android_asset/文件名称.html");

            String webPath="https://www.baidu.com/";
            WebSettings settings = webView.getSettings();

            //允许网页加载js
            settings.setJavaScriptEnabled(true);

            //js通过Name(第二个参数)字段调用类中的任何方法
            webView.addJavascriptInterface(new AndroidAndJsTest(), "Name");

            //不调用浏览器
            webView.setWebViewClient(new WebViewClient());
            webView.loadUrl(webPath);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


	//定义一个接口类
    class AndroidAndJsTest{
        @JavascriptInterface
        public void showToast(){
            Toast.makeText(MyJNI.this, "被js调用", Toast.LENGTH_SHORT).show();
        }
    }
}
原创文章 158 获赞 2 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43616001/article/details/105001391