如何在Android WebView应用中添加固定右下角的FAB悬浮按钮
Android FAB悬浮按钮实现方案
前置依赖检查
如果项目未引入Material组件库,需要先在模块级build.gradle的dependencies块中添加依赖:
implementation 'com.google.android.material:material:1.9.0'
修改后的布局代码
直接在根RelativeLayout中添加FAB作为子节点,不要放入SwipeRefreshLayout或WebView内部,避免滚动或崩溃问题:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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" tools:context=".MainActivity"> <androidx.swiperefreshlayout.widget.SwipeRefreshLayout android:id="@+id/swipe" android:layout_width="match_parent" android:layout_height="match_parent" tools:layout_behavior="@string/appbar_scrolling_view_behavior"> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent"> </WebView> </androidx.swiperefreshlayout.widget.SwipeRefreshLayout> <ProgressBar android:id="@+id/progress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_centerHorizontal="true" style="?android:attr/progressBarStyle" /> <!-- 新增悬浮分享按钮 --> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/fab_share" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentBottom="true" android:layout_margin="16dp" android:contentDescription="分享" app:srcCompat="@android:drawable/ic_menu_share" app:backgroundTint="@color/design_default_color_primary" app:tint="@android:color/white" /> </RelativeLayout>
这里顺便修正了原ProgressBar的layout_height属性,原来设为match_parent会导致居中样式异常,改为wrap_content即可正常显示。
Java功能实现代码
在MainActivity的onCreate方法中添加FAB点击逻辑,获取WebView当前页面信息调用系统分享:
// 初始化FAB FloatingActionButton shareFab = findViewById(R.id.fab_share); WebView webView = findViewById(R.id.webView); shareFab.setOnClickListener(view -> { String pageTitle = webView.getTitle(); String pageUrl = webView.getUrl(); if (pageUrl == null) { return; } // 构造分享意图 Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_SUBJECT, pageTitle); shareIntent.putExtra(Intent.EXTRA_TEXT, String.format("推荐文章:%s\n%s", pageTitle, pageUrl)); // 拉起系统分享选择器 startActivity(Intent.createChooser(shareIntent, "分享到")); });
注意事项
- SwipeRefreshLayout仅支持1个直接子View,把FAB放入该布局内会直接引发崩溃
- FAB作为根布局的子节点,层级在WebView之上,设置对齐父布局右下的属性后会固定在屏幕右下角,不会跟随WebView页面滚动
- 可自行调整FAB的margin、背景色、图标等属性适配应用样式
内容的提问来源于stack exchange,提问作者Rey
相关产品推荐
相关产品推荐

