RecyclerView (2) 横スクロールの追加

2019年12月28日土曜日

Android Kotlin RecyclerView

t f B! P L

概要

 前の例で、RecyclerViewの横幅が長く、右側に表示がはみ出す場合には、横スクロールさせる。 HorizontalScrollViewを使ふことで可能になる。RecyclerViewを囲む LinearLayoutの更に外側に、HorizontalScrollView を設ける。

横幅を無理やり広げる - each_row.xml

 RecyclerViewの表示を無理やり横に広げるため、各行に表示する項目の幅を無理やり広げる。each_row.xmlを以下のやうにする。各項目幅を 300dp に設定してゐる。


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="300dp"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="300dp"
        android:layout_height="wrap_content"/>

</LinearLayout>


Layoutの横スクロール

 main_fragment.xmlを編集し HorizontalScrollViewを適用する。

 包含関係は次のやう。

   ConstraintLayout
   │
   └─HorizontalScrollView
     │
     └─LinearLayout
       │
       └RecyclerView

 main_fragment.xml は以下のやうになる。


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.main.MainFragment">

    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">


            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/recyclerView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

        </LinearLayout>
    </HorizontalScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>

   
 Android Developersによると、HorizontalScrollViewは、子のレイアウトとして1つしか持てないとのこと。 ConstraintLayoutとHorizontalScrollViewとの関係はこれが正しいのか不明。

動作確認

 ビルドし動作確認する。2列の項目の間隔が横に広がつてゐること、横スクロールバーが表示され、横にスクロールできることを確認。
(了)

アーカイブ