notifyDataSetChanged() 不更新 RecyclerView 适配器

notifyDataSetChanged() not updating RecyclerView Adapter

我正在研究一个非常简单的 RecyclerView 实现,它显示存储在 ViewModel 中的数据。我对 Android 开发仍然很陌生,正在努力学习基础知识。在这种情况下,要存储在 ViewModel 中的所有数据都存储在一个简单的列表中,稍后我想使用 Room 来执行此操作,但现在我正在努力让事情正常进行。目前向列表中添加一个项目只是将该项目添加到ViewModel的私有成员(_mainList),public成员(mainList)没有改变,这是传递给适配器构造函数调用的成员。

视图模型:

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

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

适配器:

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
    }
}

显示列表的片段:

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 方法也使列表成为 ArrayList 和 public 可见性

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

或者,如果您想观察 ViewModel 的变化,请在您的片段中添加观察事件。 ViewModel 列表观察事件是您的最佳实践。