简体   繁体   English

单击按钮时从 recyclerview 中删除项目 - Kotlin MVVM Firestore

[英]Delete item from recyclerview on button click - Kotlin MVVM Firestore

I'm having trouble with deleting data from my Firestore collection when the user clicks a delete button in a recyclerview.当用户单击回收站视图中的删除按钮时,我无法从 Firestore 集合中删除数据。 I can delete it from the recyclerview without any problems, but I'm having trouble to make the connection between the adapter, the viewmodel and the repository that handles Firestore operations.我可以从 recyclerview 中删除它而没有任何问题,但是我无法在适配器、视图模型和处理 Firestore 操作的存储库之间建立连接。

In my adapter, I remove the item the user clicked on from the recyclerview:在我的适配器中,我从 recyclerview 中删除了用户单击的项目:

class ArticleAdapter : RecyclerView.Adapter<ArticleAdapter.ViewHolder>() {

var data = mutableListOf<Product>()
    set(value) {
        field = value
        notifyDataSetChanged()
    }

override fun getItemCount() = data.size

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

    holder.deleteButton.setOnClickListener {
        data.removeAt(position)
        notifyDataSetChanged()
    }
} ...

The recyclerview is populated after a query to the Firestore collection in my viewmodel:在对我的视图模型中的 Firestore 集合进行查询后,将填充 recyclerview:

class ArticleViewModel(private val repository: ProductRepository) : ViewModel() {

var savedProducts: MutableLiveData<MutableList<Product>> = MutableLiveData<MutableList<Product>>()

init {
    savedProducts = getProducts()
}

fun getProducts(): MutableLiveData<MutableList<Product>> {
    repository.getProducts().addSnapshotListener(EventListener<QuerySnapshot> { value, e ->
        if (e != null) {
            savedProducts.value = null
            return@EventListener
        }

        val savedProductsList: MutableList<Product> = mutableListOf()
        for (doc in value!!) {
            val item = doc.toObject(Product::class.java)
            item.id = doc.id
            savedProductsList.add(item)
        }
        savedProductsList.sortBy { i -> i.productName }
        savedProducts.value = savedProductsList
    })

    return savedProducts
}  }

In my Fragment, I'm then observing any changes that might happen to savedProducts:在我的 Fragment 中,我观察到 savedProducts 可能发生的任何变化:

class ArticleOverviewFragment : Fragment(), KodeinAware {
override val kodein: Kodein by kodein()
private val factory: ArticleViewModelFactory by instance()
private lateinit var viewModel: ArticleViewModel

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val binding: FragmentArticleOverviewBinding =
        DataBindingUtil.inflate(inflater, R.layout.fragment_article_overview, container, false)

    viewModel = ViewModelProviders.of(this, factory).get(ArticleViewModel::class.java)

    binding.viewModel = viewModel

    val adapter = ArticleAdapter()
    binding.recyclerViewGoods.adapter = adapter

    viewModel.savedProducts.observe(viewLifecycleOwner, Observer {
        it?.let {
            adapter.data = it
        }
    })

    ...
} }

Is there a way that I can observe/save the ID of the deleted item in my adapter and "transfer" that ID from the adapter to the UI where I call a function declared in the viewmodel whenever that field holding the ID is populated?有没有一种方法可以在我的适配器中观察/保存已删除项目的 ID,并将该 ID 从适配器“传输”到 UI,只要填充了包含 ID 的字段,我就会在视图模型中调用 function 声明? Or should I directly access the viewmodel from the adapter?或者我应该直接从适配器访问视图模型? Somehow, that feels kinda wrong...怎么说呢,感觉有点不对...

Declare one local variable声明一个局部变量

var removedPosition : Int ? = null

then update this variable into onClick event of deleteButton然后将此变量更新为 deleteButton 的 onClick 事件

holder.deleteButton.setOnClickListener {
        data.removeAt(position)
        removedPosition = position
        notifyDataSetChanged()
    }

Please make one method in Adapter ( ArticleAdapter )请在 Adapter ( ArticleAdapter ) 中创建一种方法

fun getRemoveItemPosition() : Int {
   var position = removedPosition
   return position;
}

which return the position of removed Item and call that method in UI( ArticleOverviewFragment ) where you will require to get position of removed item from recyclerview它返回已删除项目的 position 并在 UI( ArticleOverviewFragment )中调用该方法,您需要从 recyclerview 获取已删除项目的 position

var removedItemPosition = adapter.getRemoveItemPosition()

Now you will get value of remove item Position using variable called removedItemPosition现在您将使用名为removedItemPosition的变量获得删除项目 Position 的值


So You can get Position of removed Item in UI where you can call a function declared in the viewmodel ( ArticleViewModel ) to delete particular item in firestore collection. 因此,您可以在 UI 中获取已删除项目的 Position ,您可以在其中调用视图模型( ArticleViewModel )中声明的 function 以删除 firestore 集合中的特定项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM