Android:最新版浮动按钮的制作

UI设计给我出了个难题:在一个界面上设计一个始终位于屏幕右下角的浮动按钮
翻阅好多博客(几乎都是几年前的):都是说要导入这么一个依赖
compile ‘com.getbase:floatingactionbutton:1.10.1’,结果发现放在2021年早已失效。
几经摸索,也没找到最新版Floatactionbutton的正确依赖。

突然想到,新建项目有个Basic Activity,里面正好有这么个玩意,如图可见
在这里插入图片描述
于是新建项目,研究源码,果然适用SDK最新版本。
当然还有各种各样的坑,也顺便记录一下。

首先需要导入依赖:

    implementation 'com.android.support:design:28.0.0'
    implementation 'com.getbase:floatingactionbutton:1.10.1'

之后在xml文件里添加:

<com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="16dp"
        app:srcCompat="@drawable/dui"
        app:fabSize="normal"
        app:maxImageSize="57dp" />

其中 app:srcCompat用来更换默认按钮的icon, app:maxImageSize用来调节该icon的大小,注意图片必须长宽一致,否则错位很难看。
app:fabSize条件浮动按钮的大小,normal正常大小,mini迷你大小。
android:layout_gravity:控制按钮的位置。

最后一个问题,如何将按钮浮动到其他页面上,Basic项目是这么做的。
先设计按钮界面,然后通过 include引入底层页面,完美解决。

示例源码:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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">


    <include layout="@layout/activity_xuechang" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="16dp"
        app:srcCompat="@drawable/dui"
        app:fabSize="normal"
        app:maxImageSize="57dp" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center"
        android:layout_margin="16dp"
        app:fabSize="normal"
        app:maxImageSize="63dp"
        app:srcCompat="@drawable/jia" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|left"
        android:layout_margin="16dp"
        app:srcCompat="@drawable/cuo"
        app:fabSize="normal"
        app:maxImageSize="63dp"/>


</androidx.coordinatorlayout.widget.CoordinatorLayout>

查看效果:
在这里插入图片描述
更多有趣的项目、技巧,尽在我的微信公众号“我有一计”,内含彩蛋,待君挖掘~
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq1198768105/article/details/114793387