Android(五十七):WebView - 获取网页logo和标题、监听页面滚动、刷新页面、两端交互

展示

在这里插入图片描述

源码

web端

<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport"
        content="width=device-width,user-scalable=no,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
    <title>WebView 页面</title>
    <link rel="shortcut icon" href="./imgs/avatar.png" type="image/png">
    <link rel="stylesheet" href="./css/index.css">
    <script src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js"></script>
    <script src="./js/index.js"></script>
</head>

<body>
    <input id="text" type="text" placeholder="请输入" />
    <button onclick="handleAndroidFun()">交互</button>
    <script>
        const handleAndroidFun = () => {
            let { value } = document.getElementById('text');
            const str = Android.ShowToast(value);
            console.log(Android, str);
        }
    </script>
</body>

</html>

布局

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal"
        android:background="@color/colorPrimary"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:layout_marginBottom="5dp">

        <ImageView
            android:id="@+id/icon"
            android:layout_width="30dp"
            android:layout_height="match_parent"
            android:src="@drawable/avatar"/>

        <TextView
            android:id="@+id/title"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="@string/app_name"/>
        
        <Button
            android:id="@+id/refresh"
            android:layout_width="60dp"
            android:layout_height="match_parent"
            android:background="@android:color/transparent"
            android:text="刷新"/>

        <Button
            android:id="@+id/js_btn"
            android:layout_width="60dp"
            android:layout_height="match_parent"
            android:background="@android:color/transparent"
            android:text="调js"/>

    </LinearLayout>

    <RelativeLayout
        android:id="@+id/content_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

脚本

using Android.App;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Views;
using Android.Webkit;
using Android.Widget;
using Java.Interop;
using Java.Lang;

namespace PrimaryBlankApp
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : Activity
    {
        public static ImageView IconView;
        public static TextView TitleView;
        private WebView _webView;
        private long _exitTime;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            IconView = FindViewById<ImageView>(Resource.Id.icon);
            TitleView = FindViewById<TextView>(Resource.Id.title);
            var refresh = FindViewById<Button>(Resource.Id.refresh);
            var jsBtn = FindViewById<Button>(Resource.Id.js_btn);
            var contentLayout = FindViewById<RelativeLayout>(Resource.Id.content_layout);

            _webView = new WebView(this);
            _webView.LayoutParameters =
                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
            _webView.SetWebChromeClient(new MyWebChromeClient());
            _webView.Settings!.JavaScriptEnabled = true; // 允许执行js脚本
            // 必须,参数一为供前端使用的对象Value(仅暴露的),参数二为供前端使用的对象Key
            _webView.AddJavascriptInterface(new JavaScriptMethod(this), "Android"); 
            _webView.LoadUrl("http://10.10.1.184:5500/");

            contentLayout?.AddView(_webView);

            // 监听WebView滚动
            _webView.ScrollChange += (sender, args) => { JavaScriptMethod.ShowToast($"监听网页滚动 ---> {args.ScrollY}"); };

            // 刷新
            if (refresh != null)
                refresh.Click += delegate { _webView.Reload(); };

            // 调js
            if (jsBtn != null)
                jsBtn.Click += delegate { _webView.LoadUrl("javascript:handleAndroidFun()"); };
        }

        // 返回键
        public override void OnBackPressed()
        {
            // 判断网页是否能后退,可以则后退
            if (_webView.CanGoBack())
                _webView.GoBack();
            // 网页不能后退,则连续点击两次间隔不超过2000退出App
            else
            {
                if (JavaSystem.CurrentTimeMillis() - _exitTime > 2000)
                {
                    Toast.MakeText(this, "再按一次退出程序", ToastLength.Short)?.Show();
                    _exitTime = JavaSystem.CurrentTimeMillis();
                }
                else
                    base.OnBackPressed();
            }
        }

        // 前端的方法类
        private class JavaScriptMethod : Object
        {
            private static Context _context;

            public JavaScriptMethod(Context context)
            {
                _context = context;
            }

            // 需要引入 Mono.Android.Export.dll
            [Export("ShowToast")] // 暴露给前端的方法名称
            [JavascriptInterface] // 将方法暴露给前端
            public static string ShowToast(string str)
            {
                Toast.MakeText(_context, str, ToastLength.Short)?.Show();
                return str;
            }
        }
    }

    internal class MyWebChromeClient : WebChromeClient
    {
        public override void OnReceivedIcon(WebView view, Bitmap icon)
        {
            MainActivity.IconView.SetImageBitmap(icon);
            base.OnReceivedIcon(view, icon);
        }

        public override void OnReceivedTitle(WebView view, string title)
        {
            MainActivity.TitleView.Text = title;
            base.OnReceivedTitle(view, title);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Prosper Lee

您的赏赐将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值