Kotlin RecyclerView的点击事件

Java代码写了n多行,最近学习Kotlin语言,有点不太顺手,但最后你会发现是真的简洁。下面简单记录了一下Kotlin编写的关于RecyclerView控件的使用。

学习到什么

  • Kotlin的Android语法
  • Kotlin的接口回调
  • RecyclerView的点击事件
  • RecyclerView的分割线

Kotlin接口回调+点击事件

Adapter中的声明:

private lateinit var onItemClickListener: OnItemClickListener

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

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.tv_item.text = data?.get(position)

    holder.tv_item.setOnClickListener {
        onItemClickListener?.onItemClick(holder.itemView, position)
    }

    holder.tv_item.setOnLongClickListener {
        onItemClickListener?.onItemLongClick(holder.itemView, position)
        true
    }
}

interface OnItemClickListener{
    fun onItemClick(view: View, position: Int)
    fun onItemLongClick(view: View, position: Int)
}

Activity中的回调:

adapter?.setOnItemClickListener(object: MyAdapter.OnItemClickListener {
    override fun onItemClick(view: View, position: Int) {
        showToast("click " + position + " item")
    }

    override fun onItemLongClick(view: View, position: Int) {
        showToast("long click " + position + " item")
    }
})
recyclerview_click.jpg

完整代码:

MainActivity

class MainActivity: AppCompatActivity() {

    private var myAdapter: MyAdapter? = null
    private var myLayoutManager: LinearLayoutManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        myLayoutManager = LinearLayoutManager(this)
        myAdapter = MyAdapter(this, initData())
        my_recycler_view.layoutManager = myLayoutManager
        my_recycler_view.adapter = myAdapter
        my_recycler_view.addItemDecoration(RecycleViewDivider(this, LinearLayoutManager.VERTICAL))

        setOnClickListener()

        myAdapter?.setOnItemClickListener(object: MyAdapter.OnItemClickListener {
            override fun onItemClick(view: View, position: Int) {
                showToast("click " + position + " item")
            }

            override fun onItemLongClick(view: View, position: Int) {
                showToast("long click " + position + " item")
            }
        })
    }

    fun setOnClickListener(){
        rv_add_item.setOnClickListener{
            myAdapter?.addItem()
            myLayoutManager?.scrollToPosition(0)
        }

        rv_delete_item.setOnClickListener{
            myAdapter?.deleteItem()
        }
    }

    private fun initData(): ArrayList {
        var list = ArrayList()
        var temp = "  item"
        for (i in 1..30){
            list.add(i.toString() + temp)
        }

        return list
    }

    private fun showToast(message: String){
        Toast.makeText(applicationContext,message, Toast.LENGTH_SHORT).show()
    }
}

MyAdapter

class MyAdapter: RecyclerView.Adapter{

    private var context: Context
    private var data: ArrayList
    private lateinit var onItemClickListener: OnItemClickListener

    constructor(context: Context, data: ArrayList) : super() {
        this.context = context
        this.data = data
    }

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

    fun addItem(){
        if(data == null)
            data = ArrayList()
        data.add(0, "我是新添加的 item")
        notifyDataSetChanged()
    }

    fun deleteItem(){
        if(data == null || data.isEmpty())
            return
        data.removeAt(0)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder{
        var v = LayoutInflater.from(parent?.context).inflate(R.layout.view_item, parent, false)

        var viewHolder = ViewHolder(v)
        return viewHolder
    }

    override fun getItemCount(): Int {
        return data?.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.tv_item.text = data?.get(position)

        holder.tv_item.setOnClickListener {
            onItemClickListener?.onItemClick(holder.itemView, position)
        }

        holder.tv_item.setOnLongClickListener {
            onItemClickListener?.onItemLongClick(holder.itemView, position)
            true
        }
    }

    class ViewHolder : RecyclerView.ViewHolder{
        var tv_item : TextView

        constructor(itemView: View) : super(itemView){
            tv_item = itemView.findViewById(R.id.tv_item)
        }
    }

    interface OnItemClickListener{
        fun onItemClick(view: View, position: Int)
        fun onItemLongClick(view: View, position: Int)
    }
}

RecycleViewDivider

class RecycleViewDivider: RecyclerView.ItemDecoration {

    private var mDivider: Drawable? = null
    private var mOrientation: Int? = null

    constructor(context: Context, mOrientation: Int) {
        val a = context.obtainStyledAttributes(ATTRS)
        mDivider = a.getDrawable(0)
        a.recycle()
        setOrientation(mOrientation)
    }


    private fun setOrientation(orientation: Int){
        if(orientation != LinearLayoutManager.VERTICAL
                && orientation != LinearLayoutManager.HORIZONTAL)
            throw IllegalAccessException(".....")

        mOrientation = orientation
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State?) {
        super.onDraw(c, parent, state)

        if (mOrientation == LinearLayoutManager.VERTICAL) {
            drawVertical(c, parent)
        } else {
            drawHorizontal(c, parent)
        }
    }

    // 获取分割线尺寸
    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) {
        super.getItemOffsets(outRect, view, parent, state)

        if(mOrientation == LinearLayoutManager.VERTICAL)
            outRect.set(0,0,0,mDivider!!.intrinsicHeight)
        else
            outRect.set(0,0,mDivider!!.intrinsicWidth,0)
    }


    fun drawVertical(c: Canvas, parent: RecyclerView){
        val left = parent.paddingLeft
        val right = parent.width - parent.paddingRight
        val childCount = parent.childCount
        for (i in 0 until childCount) {
            val child = parent.getChildAt(i)
            val params = child
                    .layoutParams as RecyclerView.LayoutParams
            val top = child.bottom + params.bottomMargin +
                    Math.round(ViewCompat.getTranslationY(child))
            val bottom = top + mDivider!!.intrinsicHeight
            mDivider!!.setBounds(left, top, right, bottom)
            mDivider!!.draw(c)
        }
    }

    fun drawHorizontal(c: Canvas, parent: RecyclerView){
        val top = parent.paddingTop
        val bottom = parent.height - parent.paddingBottom
        val childCount = parent.childCount
        for (i in 0 until childCount) {
            val child = parent.getChildAt(i)
            val params = child
                    .layoutParams as RecyclerView.LayoutParams
            val left = child.right + params.rightMargin +
                    Math.round(ViewCompat.getTranslationX(child))
            val right = left + mDivider!!.intrinsicHeight
            mDivider!!.setBounds(left, top, right, bottom)
            mDivider!!.draw(c)
        }
    }

    companion object {
        private val ATTRS = intArrayOf(android.R.attr.listDivider)
    }
}

main_activity.xml




    

    

    
    


view_item.xml



    
    


你可能感兴趣的:(Kotlin RecyclerView的点击事件)