android10学习之fragment中使用webView

简单使用

在使用webView的时候。我们需要注意的是:
1.因为需要加载网络资源。所以需要配置网络加载的权限。在AndroidManifest.xml中配置
<uses-permission android:name="android.permission.INTERNET" />
2.在使用过程中,由于可能会使用http.他是明文传输的协议。所以还需要在清单文件中application节点配置
android:usesCleartextTraffic="true"
然后在布局文件中写入webView的布局

        android:id="@+id/web_index"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary" />

然后在fragment中直接调用

mWebView.loadUrl("https://m.baidu.com/?from=844b&vit=fps#");
mWebView.setWebViewClient(new WebViewClient());

就可以得到效果了。

fragment中webView的返回上级

在fragment中没有onKeyDown函数。所以我们需要设置一个监听来实现webView中放回上一级

//设置webView返回
        mWebView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
                    if (event.getAction() == KeyEvent.ACTION_DOWN) {//每次返回一级
                        mWebView.goBack();
                        return true;
                    }
                    return true;
                }
                return false;
            }
        });

webView中js函数和native函数的相互调用

本地html代码

<html>

<head>
    <meta charset="UTF-8"/>
</head>

<body>

<p>这是一个段落噻!</p>
<button onclick="userJava()">
    按钮1
</button>

</body>

<script>

        function userJava(){
            InterfaceName.method1();
        };
        function callJava(){
        //弹窗还需要一些额外设置
            alert("hello")
        }
    </script>

</html>

navive函数调用js函数

mWebView.loadUrl("javascript:callJava()");
其中callJava就是js中被调的方法

js方法调用native函数

首先创建一个类。需要被调用的方法加上@JavascriptInterface注解。

public class WebAppInterface {
    @JavascriptInterface
    public void method1() {
        Log.e("WebAppInterface", "method1");
    }

    @JavascriptInterface
    public void method2(String param1, String param2) {
        Log.e("WebAppInterface", "method2" + param1 + param2);
    }
}

并且我们还需要在fragmen中进行配置

package com.example.applicationp0.bilibili.fragment;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;

import com.example.applicationp0.MainActivity;
import com.example.applicationp0.R;
import com.example.applicationp0.bilibili.WebAppInterface;

/**
 * webView和native的交互
 */
public class IndexFragment extends Fragment {
    private Button button;
    private WebView mWebView;
    private WebSettings webSettings;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_index, container, false);
        initView(rootView);
        initListener(rootView);

        return rootView;
    }

    //设置监听
    private void initListener(View rootView) {
        //设置webView返回
        mWebView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
                    if (event.getAction() == KeyEvent.ACTION_DOWN) {//每次返回一级
                        mWebView.goBack();
                        return true;
                    }
                    return true;
                }
                return false;
            }
        });
        //button事件
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.loadUrl("javascript:callJava()");
            }
        });
    }

    //初始化视图
    @SuppressLint("SetJavaScriptEnabled")
    private void initView(View rootView) {
        mWebView = rootView.findViewById(R.id.web_index);
        button = rootView.findViewById(R.id.web_button);
        webSettings = mWebView.getSettings();
        //开启js调用
        webSettings.setJavaScriptEnabled(true);
        //允许js弹窗
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //注入调用接口方法
        mWebView.addJavascriptInterface(new WebAppInterface(), "InterfaceName");
        //网络加载
//        mWebView.loadUrl("https://m.baidu.com/?from=844b&vit=fps#");
        //本地html文件。还可以直接加载html的字符串
        mWebView.loadUrl("file:////android_asset/web/index.html");
        mWebView.setWebViewClient(new WebViewClient());
        // 由于设置了弹窗检验调用结果,所以需要支持js对话框
        // webview只是载体,内容的渲染需要使用webviewChromClient类去实现
        // 通过设置WebChromeClient对象处理JavaScript的对话框
        //设置响应js 的Alert()函数
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                AlertDialog.Builder b = new AlertDialog.Builder(getContext());
                b.setTitle("Alert");
                b.setMessage(message);
                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                });
                b.setCancelable(false);
                b.create().show();
                return true;
            }

        });
    }
}

以上就是基本使用和交互了
tips:感觉每次自己写完代码之后,就不想写博客了,觉得太麻烦了。但是想着自己每次看的博客学习的时候,网上搜出来的都是很早以前的了。由于android的版本更新比较快。以前的博客,或多或少有些问题。所以还是坚持吧。
我是一枚android小菜鸡。有机会一起交流技术。请+qq:1515914947.

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容