Androidkotlin使⽤RecyclerView⾃定义adapter实例和点击事件
1.创建adapter
class RecyclerViewAdapter(val items: List ,var context:Context) : RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>() {
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 {
= items[position]
} catch (e: Exception) {
e.printStackTrace()
}
if(mOnItemClickListener!=null){
android模拟点击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)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论