要将浮动按钮的可见性设置为GONE,可以通过监听NestedScrollView的滚动事件,当滚动到指定位置时,修改浮动按钮的可见性。
首先,需要在布局文件中定义NestedScrollView和浮动按钮:
<androidx.core.widget.NestedScrollView
android:id="@+id/nestedScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="这里是文本内容" />
</androidx.core.widget.NestedScrollView>
<Button
android:id="@+id/floatingButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:visibility="visible"
android:text="浮动按钮" />
然后,在代码中找到NestedScrollView和浮动按钮,并设置滚动监听:
NestedScrollView nestedScrollView = findViewById(R.id.nestedScrollView);
final Button floatingButton = findViewById(R.id.floatingButton);
nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
@Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
// 获取TextView的位置
TextView textView = findViewById(R.id.textView);
int[] textViewLocation = new int[2];
textView.getLocationOnScreen(textViewLocation);
int textViewTop = textViewLocation[1];
// 获取浮动按钮的位置
int[] floatingButtonLocation = new int[2];
floatingButton.getLocationOnScreen(floatingButtonLocation);
int floatingButtonTop = floatingButtonLocation[1];
// 判断浮动按钮是否到达TextView的位置
if (floatingButtonTop >= textViewTop) {
floatingButton.setVisibility(View.GONE);
} else {
floatingButton.setVisibility(View.VISIBLE);
}
}
});
这样,当NestedScrollView滚动到TextView的位置时,浮动按钮的可见性就会被设置为GONE。
领取专属 10元无门槛券
手把手带您无忧上云