当新项目添加到列表中时,我希望我的 RecyclerView 滚动到底部。下面是我的代码:
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter = new RecyclerViewAdapter(data, recyclerView);
recyclerView.setAdapter(adapter);
当我单击 下方的按钮时RecyclerView
,数据将添加到列表中:
public void addNewCard() {
data.add("New");
adapter.notifyItemInserted(data.size() - 1);
recyclerView.scrollToPosition(data.size() - 1);
}
每当我添加一个项目时,它总是会向上滚动到最高位置。我尝试使用smoothScrollToPosition()
并尝试scrollToPosition()
使用LinearLayoutManager
。我什至尝试使用ViewTreeObserver
. 也尝试更改RecyclerView
依赖项的版本。我在 Stack Overflow 上进行了彻底的搜索,没有一个解决方案适合我。
关于可能是什么问题的任何想法?我在RecyclerView
片段内使用。这可能是问题的原因吗?
我的 .xml 文件RecyclerView
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scroll_view_recycler"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="@+id/rel_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="6dp" />
<Button
android:id="@+id/button_add_new_card"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/listView"
android:layout_marginBottom="16dp"
android:layout_marginTop="8dp"
android:padding="20dp"
android:text="+ Add new Item" />
</RelativeLayout>
</android.support.v4.widget.NestedScrollView>