今天記錄一下RecyclerView的使用。
相比ListView,RecyclerView給了更大的自由度,比如監聽器自己完成(2333),最好用還是布局管理!
xml:一會會示範這三個清單,分别是橫向,豎向,瀑布流。
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="@+id/recycle_hor"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="@+id/recycle_stagger"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="@+id/recycle"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
RecyclerView可以很友善的使用橫向布局,得益于布局管理器,通過布局管理器,我們可以直接更改元件的排列方式。
代碼:這裡得MyRecycle就是我們後面自定義的了,一會會說,看看如何使用的。
//設定Recycle清單
val myRecycle = recycle
val myRecycleHor = recycle_hor
val myRecycleStagger = recycle_stagger
//瀑布流布局管理器:3列,豎向
val sym = StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL)
val lym = LinearLayoutManager(this)
val hym = LinearLayoutManager(this).apply{
this.orientation = LinearLayoutManager.HORIZONTAL
}
//豎向Recycle
myRecycle.apply{
this.layoutManager = lym
this.adapter = MyRecycle(20)
}
//橫向Recycle
myRecycleHor.apply{
this.layoutManager =hym
this.adapter = MyRecycle(10,1)
}
//瀑布流
myRecycleStagger.apply{
this.layoutManager = sym
this.adapter = MyRecycle(max = 10)
}
看看我們重寫的RecyclerView:繼承RecyclerView.Adapter泛型類型為:我們寫的内部類:MyViewHolder.
之前用ListView的同學,應該經常使用holder,現在官方內建了。
我們在holder裡擷取view的引用,當onBindViewHolder方法調用的時候,設定目前元件。
下一步:傳回視圖:onCreateViewHolder,這裡我們可以擷取目前字item的下标(this.adapterPosition),
如果需要設定監聽器給内部元件,也在這裡。下面為了示範不同類型的RecyclerView,使用了type來區分。
package iwh.com.simplewen.win0.ktcoroutinesstudy
import android.media.Image
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
/**
* recycle示例
*/
class MyRecycle(private val max:Int,private val type:Int = 0): RecyclerView.Adapter<MyRecycle.MyViewHolder>() {
inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var tv = view.findViewById<TextView>(R.id.text)
}
override fun onBindViewHolder(parent: MyViewHolder, position: Int) {
parent.tv.text = "我是第 $position 個"
}
override fun onCreateViewHolder(p0: ViewGroup, viewType: Int): MyViewHolder {
return when(type){
0-> MyViewHolder(LayoutInflater.from(p0.context).inflate(R.layout.my_recycle, p0, false)).apply {
this.tv.setOnClickListener{
Toast.makeText(p0.context,"點選:${this.adapterPosition} 個!",Toast.LENGTH_SHORT).show()
}
}
else -> MyViewHolder(LayoutInflater.from(p0.context).inflate(R.layout.my_recycle_2, p0, false)).apply{
this.tv.setOnClickListener{
Toast.makeText(p0.context,"點選:${this.adapterPosition} 個!",Toast.LENGTH_SHORT).show()
}
}
}
}
override fun getItemCount(): Int {
return max
}
}
好了。簡單記錄一下。
圖: