【问题标题】:Kotlin: passing data from fragment to recyclerviewKotlin:将数据从片段传递到recyclerview
【发布时间】:2020-06-01 15:21:37
【问题描述】:

我有一个 recyclerview,其中包含通过我的 API 加载的产品。当您单击产品时,您会被发送到信息页面,其中有一个按钮可以将该产品添加到新的回收站视图中。但我不知道如何将该产品发送到我的“愿望清单”recyclerview。 项目链接:https://github.com/arfeen14/arfeenShopApp

从 API 加载产品列表的片段。

`
class DashboardFragment : Fragment() {
    private lateinit var dashboardViewModel: DashboardViewModel
    private lateinit var notificationsViewModel: NotificationsViewModel

    private val popularProducts = arrayListOf<Producten>()
    private val popularProductsAdapter =
        MainProductAdapter(popularProducts, onClickListener = this::clickOnPopularProduct)

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        dashboardViewModel =
            ViewModelProviders.of(requireActivity())[DashboardViewModel::class.java]
        val root = inflater.inflate(R.layout.fragment_dashboard, container, false)

        val rvPopularProducten: RecyclerView = root.findViewById(R.id.rvPopularProducts)
        //rv van category
        val rvCategory: RecyclerView = root.findViewById(R.id.rvCategories)

        // connect the adapters to the recyclerviews
        rvPopularProducten.layoutManager =
            LinearLayoutManager(this.context, LinearLayoutManager.HORIZONTAL, false)
        rvPopularProducten.adapter = popularProductsAdapter

        loadData()

        return root
    }


    fun loadData() {
        dashboardViewModel.getProducts()
        popularProducts.clear()

        dashboardViewModel.product.observe(
            viewLifecycleOwner,
            Observer {
                this.popularProducts.clear()
                popularProducts.addAll(it.products)
                popularProductsAdapter.notifyDataSetChanged()
            })
    }


    private fun clickOnPopularProduct(view: View, product: Producten) {
        val transaction = requireFragmentManager().beginTransaction()
        val productInfoFragment = ProductInfoFragment()

        productInfoFragment.geselecteerdeProduct = product

        transaction.replace(R.id.nav_host_fragment, productInfoFragment)
        transaction.addToBackStack(null)
        transaction.commit()

    }
}

这是当您单击产品时显示产品信息的位置。

 class ProductInfoFragment : Fragment() {

    private lateinit var productInfoViewModel: ProductInfoViewModel
    var geselecteerdeProduct: Producten? = null

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        productInfoViewModel = ViewModelProviders.of(this).get(ProductInfoViewModel::class.java)


        val root = inflater.inflate(R.layout.product_info, container, false)

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            root.tvProducInfo_info.text =
                Html.fromHtml(geselecteerdeProduct!!.bodyHtml, Html.FROM_HTML_MODE_LEGACY)
        } else {
            root.tvProducInfo_info.text = Html.fromHtml(geselecteerdeProduct!!.bodyHtml)
        }

        Glide.with(root.context).load(geselecteerdeProduct!!.imagePath.productImgPath)
            .into(root.imgProduct_info)
        root.tvProduct_info_name.text = "€ " + geselecteerdeProduct!!.variants[0].productPrice

        root.btnAddToWishList.setOnClickListener() {
            click()

        }
        return root
    }


    private fun click() {

    }
}

如果您单击 addToWishListbtn,我想要我的产品的回收站视图。

class NotificationsFragment : Fragment() {

    private lateinit var notificationsViewModel: NotificationsViewModel
    val product = arrayListOf<Producten>()

    private val wenslijstAdapter =
        WenslijstAdapter(product)

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        notificationsViewModel =
            ViewModelProviders.of(requireActivity())[NotificationsViewModel::class.java]

        val root = inflater.inflate(R.layout.fragment_notifications, container, false)
        val rvWenslijst: RecyclerView = root.findViewById(R.id.rvWenslijst1)




        rvWenslijst.layoutManager =
            LinearLayoutManager(this.context, LinearLayoutManager.VERTICAL, false)
        rvWenslijst.adapter = wenslijstAdapter




        return root
    }


}

【问题讨论】:

  • 如何在 1 个 Fragment 和另一个 Fragment 之间导航?大约有 4 种方法可以做到这一点,因此了解这一点对于回答您的问题至关重要。
  • 哦,你有R.id.nav_host_fragment。这意味着您正在使用 Jetpack Navigation。这意味着您没有包含您的navigation.xml,因此您的问题无法回答。您永远不应该用另一个 Fragment 替换 NavHostFragment,并且永远不应该通过公共可变字段变量设置 Fragment 的参数。阅读proandroiddev.com/… 中的#5,您的应用程序将在生产环境中崩溃。

标签: android-studio android-fragments kotlin


【解决方案1】:

您可以在参数中传递项目,如下所示:

   private fun clickOnPopularProduct(view: View, product: Producten) {
    val transaction = requireFragmentManager().beginTransaction()
    val productInfoFragment = ProductInfoFragment()

    **//(psuedocode)
    val bundle = Bundle()
    bundle.putExtra(“product”, //pass your product item here)
    productInfoFragment.arguments = bundle**

    transaction.replace(R.id.nav_host_fragment, productInfoFragment)
    transaction.addToBackStack(null)
    transaction.commit()

}

在您的 ProductInfoFragment 的 onCreateView 中,您可以在扩展布局后调用:

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    productInfoViewModel = ViewModelProviders.of(this).get(ProductInfoViewModel::class.java)

    getArgs()

    val root = inflater.inflate(R.layout.product_info, container, false)


    …
     return root
}

private fun getArgs() {

  //here you can extract your extra(psedocode)
  geselecteerdeProduct = arguments?.getExtra(“product") 
}

同样的方法:

private fun click() {

}

您应该将产品作为参数传递给下一个片段。

【讨论】:

  • transaction.replace(R.id.nav_host_fragment, productInfoFragment) 如果您使用的是 NavHostFragment 和 Jetpack Navigation,则不应更换 NavHostFragment。您应该使用navigation.xml 在片段之间导航。
  • 我现在看到这个想法是从问题继承的,但是问题的代码已经不正确了。不过,使用setArguments() 代替字段变量的想法绝对是一种改进。
猜你喜欢
  • 1970-01-01
  • 2022-07-07
  • 2021-12-26
  • 2021-08-23
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多