简体   繁体   English

notifyDataSetChanged() 不更新 RecyclerView 适配器

[英]notifyDataSetChanged() not updating RecyclerView Adapter

I am working on a very simple implementation of a RecyclerView that displays data stored in a ViewModel.我正在研究一个非常简单的 RecyclerView 实现,它显示存储在 ViewModel 中的数据。 I am still very new to Android development and am trying to learn the fundamentals.我对 Android 开发还很陌生,正在努力学习基础知识。 In this situation, all the data to be stored in the ViewModel is stored in a simple list, later on I want to use Room to do this but right now I am struggling to get things working.在这种情况下,要存储在 ViewModel 中的所有数据都存储在一个简单的列表中,稍后我想使用 Room 来执行此操作,但现在我正在努力让事情正常进行。 Currently adding an item to the list only adds that item to the private member (_mainList) of the ViewModel, the public member (mainList) is unchanged, and this is the member passed into the adapter constructor call.当前向列表中添加一个项目只是将该项目添加到 ViewModel 的私有成员 (_mainList),公共成员 (mainList) 不变,这是传递给适配器构造函数调用的成员。

ViewModel:视图模型:

class ListViewModel : ViewModel() {
    private val _mainList = mutableListOf<String>()
    val mainList = _mainList.toList()

    fun addMainListItem(item: String) {
        _mainList.add(item)
    }
}

Adapter:适配器:

class MainAdapter(private var list: List<String>) :
    RecyclerView.Adapter<MainAdapter.ViewHolder>() {

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

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.itemView.list_item_text.text = list[position]
    }

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

Fragment that displays the list:显示列表的片段:

class MainListFragment : Fragment() {
    private val viewModel: ListViewModel by activityViewModels()
    private var _binding: FragmentMainListBinding? = null
    private val binding get() = _binding!!
    lateinit var adapter: MainAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentMainListBinding.inflate(inflater, container, false)
        val root: View = binding.root
        return root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // Add click listener to floating action button
        binding.fabMain.setOnClickListener {
            addListItem()
        }
        adapter = MainAdapter(viewModel.mainList)
        main_list_view.adapter = adapter
        main_list_view.layoutManager = LinearLayoutManager(requireContext())
    }
    
    private fun addListItem() {
        val input = EditText(activity)
        input.setHint("Enter the name of your new list item")
        input.inputType = InputType.TYPE_CLASS_TEXT
        activity?.let {
            val builder = AlertDialog.Builder(activity)
            builder.apply {
                setTitle("Add List Item")
                setView(input)
                setPositiveButton(
                    "Add"
                ) { dialog, id ->
                    val newItem = input.text.toString()
                    viewModel.addMainListItem(newItem)
                    adapter.notifyDataSetChanged()
                }
                setNegativeButton("Cancel"
                ) { dialog, id ->
                    dialog.cancel()
                }
            }
            builder.create()
            builder.show()
        }
    }
}
    private fun addListItem() {
        val input = EditText(activity)
        input.setHint("Enter the name of your new list item")
        input.inputType = InputType.TYPE_CLASS_TEXT
        activity?.let {
            val builder = AlertDialog.Builder(activity)
            builder.apply {
                setTitle("Add List Item")
                setView(input)
                setPositiveButton(
                    "Add"
                ) { dialog, id ->
                    val newItem = input.text.toString()
                    viewModel.addMainListItem(newItem)
                    adapter.addItem(newItem)
                }
                setNegativeButton("Cancel"
                ) { dialog, id ->
                    dialog.cancel()
                }
            }
            builder.create()
            builder.show()
        }
    }

add Method in the adapter also make list to ArrayList and public visibility适配器中的 add 方法也将列表添加到 ArrayList 和公共可见性

fun addItem(item: String){
   if(!list.contains(item)){
       list.add(item)
    }
}

Or if you want to observe changes from ViewModel then add the observing event in your fragment.或者,如果您想观察 ViewModel 的变化,请在您的片段中添加观察事件。 ViewModel list observing events is best practice in your case. ViewModel 列表观察事件是您的最佳做法。

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

相关问题 使用adapter.notifyDataSetChanged()更新RecyclerView - Updating RecyclerView with adapter.notifyDataSetChanged() Recyclerview适配器的notifyDataSetChanged不更新RecyclerView - Recyclerview Adapter's notifyDataSetChanged not updating RecyclerView 如何修复:“notifyDataSetChanged() 未更新 RecyclerView Adapter 中的 ImageView” - How to fix:'notifyDataSetChanged() not updating the ImageView in RecyclerView Adapter' recyclerview适配器notifydatasetchanged不起作用 - recyclerview adapter notifydatasetchanged not work 在 Recyclerview 适配器上设置 notifyDataSetChanged() - Set notifyDataSetChanged() on Recyclerview adapter setOnClickListener RecyclerView 适配器中的 notifyDataSetChanged - notifyDataSetChanged in setOnClickListener RecyclerView Adapter RecyclerView适配器notifyDataSetChanged不起作用 - RecyclerView Adapter notifyDataSetChanged not working Firebase Ui Paging 适配器的 notifyDataSetChanged 未更新 RecyclerView - Firebase Ui Paging adapter's notifyDataSetChanged not updating the RecyclerView notifydatasetchanged后recyclerview不更新 - recyclerview not updating after notifydatasetchanged Android RecyclerView适配器notifyDataSetChanged无法正常工作 - Android RecyclerView Adapter notifyDataSetChanged not working
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM