小编Ars*_*suf的帖子

RecyclerView在添加新项目时滚动到位置

当新项目添加到列表时,我希望我的RecyclerView滚动到底部.以下是我的代码:

RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);

adapter = new RecyclerViewAdapter(data, recyclerView);
recyclerView.setAdapter(adapter);
Run Code Online (Sandbox Code Playgroud)

当我点击下面的按钮时RecyclerView,数据会添加到列表中:

public void addNewCard() {
    data.add("New");
    adapter.notifyItemInserted(data.size() - 1);
    recyclerView.scrollToPosition(data.size() - 1);
}
Run Code Online (Sandbox Code Playgroud)

每当我添加一个项目时,它总是会滚动到最顶端的位置.我尝试使用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>
Run Code Online (Sandbox Code Playgroud)

android android-recyclerview linearlayoutmanager

13
推荐指数
3
解决办法
2万
查看次数