やりたかったこと
下記のような感じで、RecyclerViewのリストの一番下にボタンがあるレイアウトを作成しようとしていました。
(↓完成イメージ)
本来ならRecyclerViewの一部のようにボタンも一緒にスクロールされるはずです。
しかし下にボタンを配置しようとすると、RecyclerViewのスクロールタイミングとボタンがスクロールされるタイミングが異なるためおかしな挙動となってしまいます。
(下のgifだと少しわかりにくいかもしれませんが、下まで行ったスクロールを戻す時にボタンのスクロールが遅れて発生しています。)
解決策
RecyclerViewとボタンの親ビューグループにNestedScrollView
を適用させる
コードとしては下記のような形になります。
main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/main_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
<androidx.appcompat.widget.AppCompatButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="次へ" />
</androidx.appcompat.widget.LinearLayoutCompat>
</androidx.core.widget.NestedScrollView>
普通のScrollViewではなくNestedScrollViewを使うのがポイントです。
NestedScrollViewは、公式によると「入れ子スクロールをサポートしてくれる」とのことです。
今回のようにScrollViewの中にスクロールされるviewがネストされているときに使うためのビューグループということですね。
(ということはScrollViewの中にScrollViewをネストする時に使ったりもするんですかね?そんなケースあるのかわかりませんが、、、)
参考にさせていただいたサイト