RecyclerView是進階版的清單元件,它取代了基本的ListView與GridView,不只是因為RecyclerView擁有多元的呈現樣貌,而是它強制開發者實作ViewHolder類別,以實現畫面複用的機制。
指派給RecyclerView的Adapter必須繼承自RecyclerView.Adapter類別,以下說明如何使用RecyclerView
客製化Adapter與ViewHolder,MyAdapter須繼承RecyclerView.Adapter類別,並建立ViewHolder繼承自 RecyclerView.ViewHolder類別。
class MyAdapter(private val data: ArrayList<Item>, private val layout: Int):
RecyclerView.Adapter<MyAdapter.ViewHolder>() {
//實作RecyclerView.ViewHolder來儲存View
class ViewHolder(V: View): RecyclerView.ViewHolder(V){
val img_photo = v.findViewById<ImageVlew>(R.id.img_photo)
val tv_msg = v.findViewById<TextView>(R.id.tv_msg)
}
//回傳資料數量
override fun getItemcount() = data.size
//建立ViewHolder與Layout並連彼此
override fun onCreateViewHolder(viewGroup: ViewGroup, position: Int) :
ViewHolder {
val v= LayoutInflater.from(viewGroup.context).inflate(layout, viewGroup, false)
return ViewHolder (v)
}
//將資科指派給元件呈現
override fun onBindViewHolder (holder: ViewHolder, position: Int) {
holder.img_photo.setImageResource (data[position].photo)
holder.tv_msg.text = data[position].name
}
設定排列方式與方向。RecyclerView的排列方式由LayoutManager決定,最常見的是使用LinearLayoutManager與GridLayoutManager實現ListView與GridView的效果,並用LayoutManager的orientation屬性決定方向。
//建立LipearLayoutManager物件
val linearLayoutManager = LinearLayoutManager (this)
//設定清單的排列方向
linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
//連結LinearLayoutManager
recyclerView.layoutManager = linearLayoutManager
//連結adapter
recyclerView.adapter = MyAdapter(item, R.layout,adapter_horizontal)
//建立GridLayoutManager物件·並設定每欄的數量
val gridLayoutManager = GridLayoutManager(this, 3)
//設定清單的排列方向
gridLayoutManager.orientation = GridLayoutManager.VERTICAL
//連結GridLayoutManager
recyclerView.layoutManager = gridLayoutManaget
//連結adapter
recyclerView.adapter = MyAdapter(item, R.layout,adapter_vertical)