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();
        }
    }
}

除此还需要添加权限:

    <uses-permission android:name="android.permission.INTERNET"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值