できるもの
対象ファイル
- build.gradle(Module: app)
- activity_recycle_view.xml
- RecyclerViewActivity.kt
- itemList.xml
- itemList.Adapter.kt
build.gradle(Module: app)
ライブラリを読み込む。
dependencies
に implementation 'com.android.support:recyclerview-v7:28.0.0'
を追加する。バージョンは、公式サイトでチェック。
https://developer.android.com/guide/topics/ui/layout/recyclerview
activity_recycle_view.xml
RecyclerView を配置。
activity_recycle_view.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".RecycleViewActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/item_list"
android:scrollbars="vertical">
</androidx.recyclerview.widget.RecyclerView>
</androidx.appcompat.widget.LinearLayoutCompat>
RecyclerViewActivity.kt
RecyclerView を表示する Activity。
配列を用意。Adaptor とのひもづけ。
RecyclerViewActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_recycle_view.*
class RecycleViewActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recycle_view)
var itemList = arrayListOf<String>("item","item","item","item","item","item","item","item","item","item","item","item","item","item","item")
list_fragment.layoutManager = LinearLayoutManager(this)
list_fragment.adapter = ListAdapter(itemList)
}
}
itemList.xml
RecycleView 表示するリストUI。
itemList.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list_name"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:padding="20dp" android:text="item"/>
itemListAdapter.kt
先ほど作成した itemList.xml
と配列をひもづける。
itemList.Adapter.kt
class ListAdapter(private val myDataset:ArrayList<String>): RecyclerView.Adapter<ListAdapter.ViewHolder>(){
class ViewHolder(var view: View): RecyclerView.ViewHolder(view){
var listName = view.list_name
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListAdapter.ViewHolder {
val view:View = LayoutInflater.from(parent.context).inflate(R.layout.fragment_list_item,parent,false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.listName.text = myDataset[position]
}
override fun getItemCount() = myDataset.size
}
参考
https://developer.android.com/guide/topics/ui/layout/recyclerview
https://qiita.com/gitboku/items/4dc00ad0251c56e3d746
https://qiita.com/saiki-ii/items/78ed73134784f3e5db7e