适配器中的Android RecyclerView导航

时间:2019-02-08 08:18:51

标签: android kotlin android-recyclerview

我正在尝试导航到RecyclerView适配器中的片段,原因是我有一个带有带有不同文本的按钮的项目列表,并且在单击每个按钮时(取决于按钮上的文本),我希望它导航到对应于该文本的不同片段。处理此导航的最佳方法是什么?

     class DummyAdapter(val context: Context, private var DummyList: ArrayList<DummyModel>) :
        RecyclerView.Adapter<DummyAdapter.DummyViewHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, p1: Int): DummyViewHolder {
            val dummyBinding: ListItemDummyBinding = DataBindingUtil.inflate(
                LayoutInflater.from(parent.context),
                R.layout.list_item_dummy,
                parent,
                false
            )
            return DummyViewHolder(dummyBinding)
        }

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

        override fun onBindViewHolder(holder: DummyViewHolder, position: Int) {
            val item = dummyList[position]
            holder.bind(item)

            holder.dummyItemBinding.buttonDummy.setOnClickListener {
                if (holder.dummyItemBinding.buttonDummy.text == "Fragment 1") {

                    //The actual Navigation Logic to be added
                }
            }
            holder.dummyItemBinding.buttonDummy.setOnClickListener {
                if (holder.dummyItemBinding.buttonDummy.text == "Fragment 2") {

                    //The actual Navigation Logic to be added
                }

            }
        }

            inner class DummyViewHolder(var dummyItemBinding: ListItemDummyBinding) :
                RecyclerView.ViewHolder(dummyItemBinding.root) {
                private lateinit var dummyItem: DummyModel
                fun bind(dummyItem: DummyModel) {
                    this.dummyItem = dummyItem
                    dummyItemBinding.buttonDummy.text = dummyItem.button_text
                }
            }
   }

1 个答案:

答案 0 :(得分:0)

您可以这样做:

将回调传递给适配器

class DummyAdapter(
    val context: Context, 
    private var DummyList: ArrayList<DummyModel>,
    private val onButtonClickedListener: (buttonText: String) -> Unit
): RecyclerView.Adapter<DummyAdapter.DummyViewHolder>() {
// ...
override fun onBindViewHolder(holder: DummyViewHolder, position: Int) {
    val item = dummyList[position]
    holder.bind(item)
    holder.dummyItemBinding.buttonDummy.setOnClickListener {
        val buttonText = holder.dummyItemBinding.buttonDummy.text
        onButtonClickedListener(buttonText)
    }
}

当您创建适配器时,请引用功能:

val adapter = DummyAdapter(context, dummyList, ::onDummyItemClicked)

fun onDummyItemClicked(buttonText: String) {
    when(buttonText) {
        "Fragment 1" -> goToFragment1()
        "Fragment 2" -> goToFragment2()
    }
}