[英]How to hide Floating Action Button when scrolled on ScrollView? Android - Kotlin
I cannot able to find a solution to hide Floating Action Button when scrolled on ScrollView.在 ScrollView 上滚动时,我无法找到隐藏浮动操作按钮的解决方案。 I can find some solutions but all of them are for Java, there is no valid solution for Kotlin.
我可以找到一些解决方案,但它们都是针对 Java 的,Kotlin 没有有效的解决方案。
You can see my layout below:你可以在下面看到我的布局:
<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"
android:fillViewport="true">
<ScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".ZekatFragment">
<!-- MAIN CONTENT -->
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/floating_action_button"
style="@style/Widget.MaterialComponents.FloatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_marginBottom="10dp"
android:layout_marginEnd="5dp"
app:backgroundTint="@color/colorPrimary"
app:fabSize="mini"
app:srcCompat="@drawable/ic_arrow_downward_white"
app:tint="#FFFFFF" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
This is the java version convert it to kotlin version.这是将其转换为 kotlin 版本的 java 版本。
mScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
final static int SHOW_THRESHOLD = 120;
float prevY = 0;
@Override
public void onScrollChanged() {
//LOGI(TAG, "Scroll Y = " + mScrollView.getScrollY());
float scrollY = mScrollView.getScrollY();
if (fab != null) {
if (mScrollView.getScrollY() > 0) {
fab.hide();
} else {
fab.show();
}
}
if (scrollY > SHOW_THRESHOLD && mControlsVisible) {
onHide();
mControlsVisible = false;
} else if (scrollY == 0 && !mControlsVisible) {
onShow();
mControlsVisible = true;
}
}
});
Simply You can use setOnScrollChangeListener
to get scroll position on run time.只需您可以使用
setOnScrollChangeListener
在运行时获取滚动位置。
An example of code will look like this代码示例如下所示
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
scrollView.setOnScrollChangeListener(object : View.OnScrollChangeListener {
override fun onScrollChange(v: View?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) {
val x = scrollY - oldScrollY
if (x > 0) {
//scroll up
//show fab icon
} else if (x < 0) {
//scroll down
//hide fab icon
} else {
}
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.