kotlin onClick在RecyclerView从Firestore

q43xntqr  于 2023-04-12  发布在  Kotlin
关注(0)|答案(2)|浏览(163)

我有一个RecyclerView列表,在其中显示来自Firestore的所有文档(每个文档都有自己的带有数据的集合),问题是当单击列表项时,如何在新片段中显示来自Firestore的其相应数据
My Firestore collection

在Recycler视图中,我只显示每个项目的名称和图像,但在单击项目后,我想打开一个新片段,其中包含集合中的所有字段
视图模型

class MainViewModel: ViewModel() {
    private val db = FirebaseFirestore.getInstance()
    private val auth = FirebaseAuth.getInstance()
    private val documentsLiveData = MutableLiveData<List<Card>>()

    fun getDocuments() {
        if (auth.currentUser != null){
            db.collection("cards")
                .get()
                .addOnSuccessListener { documents ->
                    val cardList = mutableListOf<Card>()
                    for (document in documents) {
                        val card = document.toObject(Card::class.java)
                        cardList.add(card)
                    }
                    documentsLiveData.value = cardList
                }
                .addOnFailureListener { exception ->
                    Log.e("Document error", exception.message.toString())
                }
        }
        else{
            Log.e("Document error", "Toast error")
        }

    }

    fun getDocumentsLiveData(): LiveData<List<Card>> {
        return documentsLiveData
    }
    

}

适配器

class CardAdapter(private val context: Context,
                  private val list: List<Card>) : RecyclerView.Adapter<CardAdapter.MyViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
        return MyViewHolder(view)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val item = list[position]
        holder.itemView.card_name.text = item.name
        holder.itemView.card_description.text = item.description
        Glide.with(context)
            .load(item.img)
            .into(holder.itemView.card_img)
    }

    override fun getItemCount(): Int {
        return list.size

    }

    class MyViewHolder(view: View) : RecyclerView.ViewHolder(view){

    }
}

主片段

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewModel = ViewModelProvider(this)[MainViewModel::class.java]

        viewModel.getDocumentsLiveData().observe(viewLifecycleOwner) { cardList ->
            binding.progBar.visibility = View.GONE
            val adapter = CardAdapter(requireContext(), cardList)
            binding.mainRecycler.adapter = adapter
        }
        viewModel.getDocuments()
    }

我试着按元素id搜索,但没有成功

xfb7svmp

xfb7svmp1#

要在单击列表项时在新片段中显示Firestore中的相应数据,您可以按照以下步骤操作:
在CardAdapter中,将单击侦听器添加到onBindViewHolder方法中的项目视图:

override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
    val item = list[position]
    holder.itemView.card_name.text = item.name
    holder.itemView.card_description.text = item.description
    Glide.with(context)
        .load(item.img)
        .into(holder.itemView.card_img)

    holder.itemView.setOnClickListener {
        val action = MainFragmentDirections.actionMainFragmentToDetailFragment(item.id)
        it.findNavController().navigate(action)
    }
}

在MainFragment中,创建一个新的NavDirections对象,其中包含文档ID作为参数:

val action = MainFragmentDirections.actionMainFragmentToDetailFragment(item.id)

创建一个新的DetailFragment,它将显示来自Firestore的相应数据。在DetailFragment的onCreateView方法中,从参数中检索文档ID,并使用它来查询Firestore以获得相应的文档:

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val args = DetailFragmentArgs.fromBundle(requireArguments())
    val db = FirebaseFirestore.getInstance()
    val docRef = db.collection("cards").document(args.documentId)

    docRef.get().addOnSuccessListener { document ->
        if (document != null) {
            val card = document.toObject(Card::class.java)
            // Display the data in the UI
        } else {
            Log.d(TAG, "No such document")
        }
    }.addOnFailureListener { exception ->
        Log.d(TAG, "get failed with ", exception)
    }

    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_detail, container, false)
}

在DetailFragment中,在UI中显示来自Firestore的相应数据。您可以使用在步骤3中从Firestore检索的card对象来填充UI元素。

qxgroojn

qxgroojn2#

最佳方式:首先显示收藏列表,然后显示选择收藏的文件/收藏列表。

相关问题