Kotlin学习一 制作RecyclerView列表

 
  

1、相对于java中Recyclerview的setLayoutManger、setAdapter 写法变更为

recy = findViewById(R.id.main2_recy) as RecyclerView?
recy?.layoutManager = LinearLayoutManager(this)

list = ArrayList()
for (i :Int in 1..5){
    list?.add(Studio("张三","","20"))
}
recy?.adapter = adapters(this,list)

2、获取控件方式变换为 
recy = findViewById(R.id.main2_recy) as RecyclerView?
适配器处理 适配器处理方面网上有三种教程,我这个是根据studio提示的方法来生成的适配器
  

class adapters : RecyclerView.Adapter {

    private var context: Context

    private var list: ArrayList?

    constructor(context: Context, list:ArrayList?){
        this.context = context
        this.list = list
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): Holder {
        //TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        return Holder(View.inflate(parent?.context,R.layout.item_recy,null))
    }

    override fun getItemCount(): Int {
        //TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        return list?.size as Int
    }

    override fun onBindViewHolder(holder: Holder?, position: Int) {
        //TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        holder?.tv?.setText(list?.get(position)?.name)
        holder?.tv?.setOnClickListener({

        })
    }

    class Holder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
      var tv:TextView =   itemView?.findViewById(R.id.item_tv) as TextView
    }

}

注意 TODO是需要处理的有点类似于java的//todo,但是不同的是,因为它的方法告诉我们,它会抛出一个异常,也就
是上面这个方法会导致程序崩溃。它的好处是:配合IDE自动声明的TODO, 会强制开发者去实现这个TODO或者删除它。


 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
 

你可能感兴趣的:(Kotlin学习一 制作RecyclerView列表)