0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

RecyclerViewの下にボタンを配置して一緒にスクロールさせたい

Last updated at Posted at 2022-08-27

やりたかったこと

下記のような感じで、RecyclerViewのリストの一番下にボタンがあるレイアウトを作成しようとしていました。
(↓完成イメージ)
完成イメージ.gif

本来ならRecyclerViewの一部のようにボタンも一緒にスクロールされるはずです。
しかし下にボタンを配置しようとすると、RecyclerViewのスクロールタイミングとボタンがスクロールされるタイミングが異なるためおかしな挙動となってしまいます。
(下のgifだと少しわかりにくいかもしれませんが、下まで行ったスクロールを戻す時にボタンのスクロールが遅れて発生しています。)

挙動おかしい.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をネストする時に使ったりもするんですかね?そんなケースあるのかわかりませんが、、、)

参考にさせていただいたサイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?