到达嵌套滚动视图末尾时显示另一个背景



我已经在许多网站上检查了这个概念,并希望在我的应用程序中实现它。这个想法很简单,有一个静态背景,例如在应用程序中使用颜色作为背景,当滚动结束时,它会在底部显示一些树。

这就像将第二个背景放在滚动视图的底部一样。我尝试只放置背景,但它显示在应用程序的底部,而不是滚动视图中。

有没有办法做到这一点? 因为我已经搜索过,没有找到任何可靠的来源。

如果我理解正确,您可以使用此XML布局(或以编程方式构建相同的结构)实现所需的内容。

你只需要把一个ImageView和你的可绘制对象作为"src"放在NestedScrollView的ViewGroup底部(因为ScrollView只能有一个子视图)。你会得到一个滚动视图,里面有一个ViewGroup,你的内容后跟你的图像。

当用户滚动到内容下方的底部时,图像将从底部显示。在下面的代码中,我向您展示了 XML,以及您可以在何处设置应用程序的背景、滚动视图的底部以及放置内容的位置。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:background="@drawable/app_background">
<!-- YOU CAN SET YOUR APP BACKGROUND COLOR OR DRAWABLE UP HERE -->
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!-- YOUR CONTENT GOES HERE -->
<TextView android:text="Your content here instead of this TextView"
android:layout_width="match_parent" 
android:layout_height="1500dp" />

<!-- YOUR FOOTER IMAGE HERE -->
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/trees" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</LinearLayout>

如果希望底部的图像显示在 ScrollView内容后面而不是下方,则需要删除上述 XML 中的ImageView,而是将背景可绘制对象设置为NestedScrollView 中的 LinearLayout,并使用以下 XML 资源可绘制对象作为背景:

<?xml version="1.0" encoding="utf-8"?>
<bitmap
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/trees"
android:gravity="bottom|center_horizontal" />

此 XML 将创建一个新的可绘制对象,当设置为背景时,该可绘制对象与视图底部对齐。只需将该代码保存在可绘制文件夹中名为 trees_background.xml 的 xml 文件中,然后将 LinearLayout 更改为

android:background="@drawable/trees_background.xml"

如果我理解正确,实现所需行为的最简单方法是向回收商的适配器添加额外的ViewType,并将此项目添加到项目列表的末尾。它将用作回收器视图的页脚,因此当用户滚动到底部时,他们会看到您的树木或任何东西。

你可以通过以下方式检测你是否已经到达了NestedScrollView的底部,然后可以应用自己的逻辑来相应地改变背景。

NestedScrollView nestedScrollView = (NestedScrollView) findViewById(R.id.nestedScrollView);
nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
@Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
if (scrollY < oldScrollY) {
// Scroll UP
} else if (scrollY > oldScrollY) {
//Scroll down
} else if (scrollY == 0) {
// TOP SCROLL
} else if (scrollY == (v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight())) {
//You have reached  the bottom of nested scrollview
//Add you logic here to change background
}
}
});

希望我答对了你。

最新更新