今天记录一下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() {
inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var tv = view.findViewById(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
}
}
好了。简单记录一下。
图: