Android kotlin使用RecyclerView自定义adapter实例和点击事件

1.创建adapter
class RecyclerViewAdapter(val items: List ,var context:Context) : RecyclerView.Adapter() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
var view = LayoutInflater.from(context).inflate(R.layout.item_app_info, parent, false)
return ViewHolder(view)
}
private var mOnItemClickListener: OnItemClickListener?=null
override fun getItemCount(): Int = items.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        try {
            holder.mAppName.text = items[position]
        } catch (e: Exception) {
            e.printStackTrace()
        }
        if(mOnItemClickListener!=null){
            var position = holder.layoutPosition
            holder.itemView.setOnClickListener {
                mOnItemClickListener!!.onItemClick(holder.itemView, position)
            }
        }
    }
    interface OnItemClickListener {
        fun onItemClick(view: View, position: Int)
    }

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
        this.mOnItemClickListener = onItemClickListener
    }

    class ViewHolder(var view: View) : RecyclerView.ViewHolder(view){
         var mAppName: TextView = view.findViewById(R.id.tv_app_name)
    }

}
2.在 acitivity里的使用
val arraylist = Arrays.asList("231","w1","yu1")
    var recyclerViewAdapter = RecyclerViewAdapter(arraylist,context)
    recyclerViewAdapter!!.setOnItemClickListener(object : RecyclerViewAdapter.OnItemClickListener{
        override fun onItemClick(view: View, position: Int) {
            Toast.makeText(context," text is ${arraylist[position]}",Toast.LENGTH_SHORT).show()
        }
    })
    activity_recyclerview.adapter = recyclerViewAdapter
    activity_recyclerview.layoutManager = LinearLayoutManager(this)

你可能感兴趣的:(kotlin和ndk)