如何在嵌套滚动视图中向上滚动时将单击侦听器设置为嵌套滚动视图



您好,我有一个嵌套的滚动视图,我想在单击侦听器时设置为嵌套滚动视图,以便在向上滚动嵌套滚动视图时它执行某些操作,例如显示一个 Toast 显示向上滚动时向上滚动嵌套滚动视图,以及当我向下滚动嵌套滚动视图时显示向下滚动的 Toast

这是我的嵌套滚动视图


<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"
app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="5dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/lorem_ipsum"
/>
</LinearLayout>
</androidx.core.widget.NestedScrollView>

为滚动视图分配一个 id


<androidx.core.widget.NestedScrollView
android:id="@+id/nested_scroll_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"
app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="5dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/lorem_ipsum"
/>
</LinearLayout>
</androidx.core.widget.NestedScrollView>

声明滚动视图


NestedScrollView nestedScrollView;

按 id 查找滚动视图


nestedScrollView = view.findViewById(R.id.nested_scroll_view);

将滚动时更改侦听器设置为嵌套的滚动视图


nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
@Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
if (scrollY>scrollX){
Toast.makeText(getContext(), "Scrolling Down", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Scrolling Up", Toast.LENGTH_SHORT).show();
}
}
});

瞧,将您的操作放在 if 语句中

我认为您可以使用SwipeRefreshLayout而不是NestedScrollView。您可以使用回调来管理滚动功能。

最新更新