2

我正在创建 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
    })
}

笔记适配器

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 上。这真的很烦人。请帮忙 !!

4

2 回答 2

0

你是在调用 submitList() 之后调用 notifyDataSetChanged() 吗?

于 2021-05-28T08:00:14.180 回答
0

检查哪些块内部when语句被调用truefalse

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

visibilty = View.VISIBLEfalse块内

于 2021-05-28T16:04:40.437 回答