- 描述:模仿某网盘app,悬浮按钮随着上下滑动,消失/显示的一个小功能。
- 难度:初级
- 知识点:Visibility(显示/消失),setOnScrollListener事件
模仿某网盘悬浮按钮随着上下滑动,消失/显示
一、UI界面设计
首先,需要学习本栏目下的Adapter适配器知识,如果还想让悬浮Button看起来更加美观,则需要学习同栏目下的Button设计的知识
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="?attr/actionBarSize">
<!-- 图层一:基础模块 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="40dp"
android:gravity="center">
<!-- listFile模块 -->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/r2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"/>
</LinearLayout>
<!-- 图层二:切换图层三按钮 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="right|bottom"
android:paddingRight="15dp">
<Button
android:id="@+id/xf_btn"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginBottom="10dp"
android:layout_marginRight="10dp"
android:background="@drawable/shape"
android:text="+"
android:textColor="#FFF"
android:textSize="45dp"/>
</LinearLayout>
</RelativeLayout>
二、setOnScrollListener事件的使用
关于setOnScrollListener事件的信息,在官方文档里有详细介绍,我就不做文抄公了。他在此处主要作用是 获取当前RecyclerView上下滑动的距离,如果滑动距离 y>0 就隐藏悬浮按钮(GONE),y<0 就显示悬浮按钮(VISIBLE),逻辑非常简单。
private void onclick() {
r2 = findViewById(R.id.r2);
xf_btn = findViewById(R.id.xf_btn);
r2.setOnScrollListener(new RecyclerView.OnScrollListener() {
/**
* Callback method to be invoked when the RecyclerView has been scrolled. This will be
* called after the scroll has completed.
* <p>
* This callback will also be called if visible item range changes after a layout
* calculation. In that case, dx and dy will be 0.
*
* @param recyclerView The RecyclerView which scrolled.
* @param dx The amount of horizontal scroll.
* @param dy The amount of vertical scroll.
*/
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (dy > 0) {
xf_btn.setVisibility(View.GONE); // 隐藏添加按钮
} else {
xf_btn.setVisibility(View.VISIBLE);
}
}
});
}