新しいアイテムがリストに追加されたときに 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()
みたり、つけてみたり。私も使ってみました。依存関係のバージョンも変更しようとしました。Stack Overflow で徹底的に検索しましたが、どのソリューションも機能しません。scrollToPosition()
LinearLayoutManager
ViewTreeObserver
RecyclerView
何が問題になる可能性があるかについてのアイデアはありますか? 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>