如何在AndroidKotlin中从ViewModel导航到片段

qgelzfjb  于 2023-01-05  发布在  Kotlin
关注(0)|答案(1)|浏览(188)

我有一个视图模型,我添加了一个单击事件侦听器。我如何从该视图模型导航到一个片段
视图模型代码

class PromoAdapter(var promo: ArrayList<PromoModal>) :
    RecyclerView.Adapter<PromoAdapter.UserViewHolder>() {

    override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
        holder.bind(promo[position])
        holder.promoRow.setOnClickListener() {
            // Navigate to Fragment with name UserFragment
           
        };
    }
}

用户碎片编码

class UserFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View? {
        val view: View = LayoutInflater.from(container!!.context)
            .inflate(R.layout.user_page_fragment, container, false)
   }
}

我试过写下面的代码仍然不工作
在ViewModel中单击事件

val intent = Intent(itemView.context, UserFragment::class.java)
itemView.context?.startActivity(intent)

我找不到工作的东西,任何帮助都将不胜感激

t9aqgxwy

t9aqgxwy1#

最好将click侦听器移动到片段中
适配器中:

class PromoAdapter(
    var promo: ArrayList<PromoModal>,
    val openFragment: (promoModal: PromoModal) -> Unit
  ) :
    RecyclerView.Adapter<PromoAdapter.UserViewHolder>() {

    override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
        holder.bind(promo[position])

        val currentItem = promo.getOrNull(position) ?: return

        holder.promoRow.setOnClickListener {
            openFragment(currentItem)
           
        };
    }
}

在片段中:

val mAdapter = PromoAdapter(
     promo = promoList,
     openFragment = { promoModal ->
          // Navigate to Fragment with name UserFragment 
     }
   )

相关问题