我试图让floatingActionButton
隐藏在向下滚动并再次显示向上滚动时,我使用setOnScrollChangeListener
为ScrollView做这个
XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".DetailsActivity"
android:orientation="vertical">
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_anchor="@id/linearLayout"
app:layout_anchorGravity="start|bottom"
android:layout_margin="16dp"
android:src="@drawable/icons8_share_480"
/>
码
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
if (scrollY > 0 && fab.isShown()) {
fab.setVisibility(View.GONE);
} else if (scrollY < 0) {
fab.setVisibility(View.VISIBLE);
}
}
});
} else {
scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
int mScrollY = scrollView.getScrollY();
if (mScrollY > 0 && fab.isShown()) {
fab.setVisibility(View.GONE);
} else if (mScrollY < 0) {
fab.setVisibility(View.VISIBLE);
}
}
});
}
qazxsw poi。 它似乎有效,但有时候滚动制作没有出现两个问题,第二个它直接消失没有任何影响,在这个GIF qazxsw poi更明确。
问题是因为你从顶部滚动到底部之后它是真的它将被隐藏但是它无法知道你何时滚动到顶部因为你位置上的the result不是真正小于0.尝试使用这里的代码,它可以给出旧位置和新位置然后你可以比较它所以它会知道你何时开始滚动到顶部或底部
这是链接:Destination
感谢@JEFF,在监视mScrollY < 0
之后,我将条件中的值更改为
https://stackoverflow.com/a/33230992/10396176,它又出现了。
关于第二个问题,我搜索如何做动画,我发现有两种方法可以做到这一点
首先是使用OnScrollChangeListener
和scrollY < 22
而不是方法fab.hide
编辑后的代码
fab.show
第二种方式是使用自定义缩放动画来放大,缩小,就像这个qazxsw poi