在Android中使用Kotlin在RecyclerViewAdapter中实现自定义界面

时间:2020-04-30 19:13:51

标签: android kotlin android-recyclerview

我的应用程序中实现了RecyclerView。由于性能差异,我想使用notifyItemRemoved和notifyItemChanged而不是setDataChange来远程更改,添加和删除项目,而不是通过setDataChange进行更改。我想做一些接口对象,但我无法弄清楚如何或在何处实现和覆盖接口方法等。

这是我在MainActivity.kt中实现RecyclerView

val linearLayoutManager = LinearLayoutManager(this)
    recyclerView.layoutManager = linearLayoutManager

    adapter = RecyclerAdapter(itemList)
    recyclerView.adapter = adapter

这是我的界面

public interface AddItemListener {
    void addItem(int position);
}

这是我的RecyclerView类及其ViewHolder:

class RecyclerAdapter(val items: ArrayList<RecyclerViewListModel>) :
RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>() {


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        MyViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_recycler_view, parent, false))

    override fun getItemCount(): Int = items.size

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.onBind()
    }


    inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun onBind(){}
    }

}

我在MainActivity中有Floating按钮。我想访问Viewholder以便添加元素。预先感谢!

1 个答案:

答案 0 :(得分:1)

像这样向适配器添加侦听器:

class RecyclerAdapter(val items: ArrayList<RecyclerViewListModel>, internal var listener: AddItemListener) :
RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>() {


override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
    MyViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_recycler_view, parent, false))

override fun getItemCount(): Int = items.size

override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
    holder.onBind()
}

fun addNewItem(item : RecyclerViewListModel){
   items.add(item)
   notifyItemInserted(items.size - 1)
}

fun removeItem(position : Int){
   items.removeAt(position)
   notifyItemRemoved(position)
}

inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
    View.OnClickListener {
    override fun onClick(v: View?) {
        listener. addItem(adapterPosition)
    }

    init {
        itemView.setOnClickListener(this)
    }

    fun onBind(){}
  }
}

在活动/片段中添加点击侦听器:

adapter = RecyclerAdapter(itemList, this)

实现AddItemListener的乐趣:

override fun addItem(int position){
   // you can get item click position
   // you can show the dialog as like "Do you want to delete?"
   adapter.romoveItem(position) 
}

添加新项目:

val fab: FloatingActionButton = findViewById(R.id.fab)
fab.setOnClickListener { view ->
     adapter.addNewItem(RecyclerViewListModel(verb1, verb2....))
}