環境メモ
⭐️macOS Monterey
⭐️Android Studio Chipmunk 2021.2.1 Patch 2
Android デベロッパーの公式サイトにある「RecyclerView サンプルアプリ(Kotlin)」のサンプルプログラムにフッターを追加してみました。
「RecyclerView サンプルアプリ(Kotlin)」のサンプルプログラム
Android デベロッパー(RecyclerView)
https://developer.android.com/guide/topics/ui/layout/recyclerview?hl=ja
RecyclerView サンプルアプリ(Kotlin) GitHubページ
https://github.com/android/views-widgets-samples/tree/main/RecyclerViewKotlin/
↑RecyclerViewKotlin
フッターのレイアウト
footer_item.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:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/pink">
<TextView
android:id="@+id/footerTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:textSize="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="footer" />
</androidx.constraintlayout.widget.ConstraintLayout>
フッターのRecyclerView(FooterAdapter)
FooterAdapter.kt
package com.example.recyclersample.flowerList
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.recyclersample.R
/**
* FooterAdapter
* 表示内容を更新する
*/
class FooterAdapter: RecyclerView.Adapter<FooterAdapter.FooterViewHolder>() {
/**
* RecyclerView.ViewHolder
* 描画するためのViewを保持する。再利用される。
*/
class FooterViewHolder(view: View): RecyclerView.ViewHolder(view) {
private val footerTextView: TextView = itemView.findViewById(R.id.footerTextView)
fun bind() {
footerTextView.text = "フッターだよぉん"
}
}
/**
* onCreateViewHolder
*/
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FooterViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.footer_item,parent,false)
return FooterViewHolder(view)
}
/**
* onBindViewHolder
* 表示内容の入れ替え
*/
override fun onBindViewHolder(holder: FooterViewHolder, position: Int) {
holder.bind()
}
/**
* getItemCount
* フッター1件
*/
override fun getItemCount(): Int {
return 1
}
}
FlowersListActivity.kt
ヘッダーと、フラワーリストの後に、フッターを追加する。
ConcatAdapter
複数のアダプターの内容を順番に表示する実装
FlowersListActivity.kt
〜省略
val headerAdapter = HeaderAdapter()
val flowersAdapter = FlowersAdapter { flower -> adapterOnClick(flower) }
val footerAdapter = FooterAdapter()
//val concatAdapter = ConcatAdapter(headerAdapter, flowersAdapter)
// フッターを追加する
val concatAdapter = ConcatAdapter(headerAdapter, flowersAdapter, footerAdapter)
val recyclerView: RecyclerView = findViewById(R.id.recycler_view)
recyclerView.adapter = concatAdapter
〜省略
完成!!