RecyclerView 重复提交列表时不显示所有数据

RecyclerView not display all data when submiting list repeatedly

我正在创建 Notes 应用程序,它显示来自本地数据库的用户 Notes。该应用程序运行良好,但当我尝试多次搜索(查询)笔记时,某些数据未显示。

应用程序的屏幕截图:

NotesViewModel

class NotesViewModel(private val database: NotesDao) : ViewModel() {
    fun searchNotes(string: String) = database.searchNote(string)
}

笔记片段

binding.searchEditText.doOnTextChanged { text, _, _, _ ->
    notesViewModel.searchNotes("%$text%").observe(viewLifecycleOwner, {
        adapter.submitList(it)
        Log.v("NotesFragment: ", it.toString())           //Log return expected data
    })
}

NotesAdapter

class NotesAdapter(private val clickListener: NoteClickListener) : ListAdapter<Notes, NotesAdapter.NotesViewHolder>(NotesDiffCallBack()) {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NotesViewHolder {
        return NotesViewHolder.from(parent)
    }

    override fun onBindViewHolder(holder: NotesViewHolder, position: Int) {
        val item = getItem(position)
        holder.bind(clickListener, item)
    }
    
    class NotesViewHolder private constructor(private val binding: ListItemNotesBinding) : RecyclerView.ViewHolder(binding.root) {

        fun bind(clickListener: NoteClickListener, item: Notes) {
            binding.note = item
            binding.clickListener = clickListener
            binding.executePendingBindings()
        }
        .......
    }
}

BindingUtil

@BindingAdapter("noteTitle")
fun TextView.setNoteTitle(item: Notes?) {
    item?.let {
        Log.v("BindingUtil ", "title -> "+ it.noteTitle)     // Log return expected data
        when (it.noteTitle.isEmpty()) {
            true -> visibility = View.GONE
            false -> text = item.noteTitle
        }
    }
}

list_item_notes.xml

<data>
    <variable
        name="note"
        type="com.example.notes.db.Notes" />
<data/>
...
<TextView
    android:id="@+id/note_title_textview"
    app:noteTitle="@{note}" />

NotesAdapter 中的 NotesDiffCallBack

class NotesDiffCallBack : DiffUtil.ItemCallback<Notes>() {
    override fun areItemsTheSame(oldItem: Notes, newItem: Notes): Boolean {
        return oldItem.noteId == newItem.noteId
    }

    override fun areContentsTheSame(oldItem: Notes, newItem: Notes): Boolean {
        return oldItem == newItem
    }
}

数据库返回的'note'数据是正确的。 即使 Log.v() 在 'NotesFragment' 和 'BindingUtil' 中显示正确的 'note' 数据, 但不会在 UI 上显示。 这真的很烦人。请帮忙!!

您是否在调用 submitList() 之后调用 notifyDataSetChanged()?

检查 when 语句中的哪些块被调用 truefalse

如果它按预期执行 false 然后尝试设置

visibilty = View.VISIBLEfalse 块内