带空间的自动完成文本视图

2024-04-09

我有一个 Room 数据库并创建了一个模型和 viewModel。我想知道如何使自动完成文本视图与数据库数据和视图模型一起工作,以在用户输入时过滤客户列表

视图模型

class CustomerVM : ViewModel() {
    private val customers: MutableLiveData<List<Customer>> by lazy {
        loadCustomers()
    }

    fun getCustomers(): LiveData<List<Customer>> {
        return customers
    }

    private fun loadCustomers() : MutableLiveData<List<Customer>> {
        return DataModel.getInstance().roomDb.CustomerDao().getAllCustomers() as MutableLiveData<List<Customer>>
    }
}

如果我了解您希望将其作为自动完成文本的条目,请查看内部数据库中的数据。

为此,我使用 allStudentsData 创建自定义 ViewModel,存储来自活动的侦听

  1. 存储库类 直接从数据库监听的存储库

    val allStudents: LiveData<List<Student>> = studentDao.getAll()

  2. 视图模型类

   init {
        val studentsDao = AppDatabase.getDatabase(application,viewModelScope).studentsDao()
        studentRepository = StudentRepository(studentsDao)
        allStudents = studentRepository.allStudents
    }
  1. 活动课
    private lateinit var studentViewModel: StudentViewModel

    public override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        studentViewModel = ViewModelProvider(this).get(StudentViewModel::class.java)
        studentViewModel.allStudents.observe(this, Observer { students ->
            // Update the cached copy of the students in the adapter.
            students?.let {
                val arr = mutableListOf<String>()

                for (value in it) {
                    arr.add(value.name)
                }
                val adapter: ArrayAdapter<String> =
                    ArrayAdapter(this, android.R.layout.select_dialog_item, arr)
                names.setAdapter(adapter)
            }
        })
    }

在活动中,我们有一个 viewModel 变量,用于观察在数据库中插入新记录时更改的数据。 当我们有新数据时,Observer {} 被调用,因此我们使用新的学生列表创建一个可变列表,添加所有学生并设置适配器

通过这样做,当数据库中的数据发生变化时

DB====>存储库====>视图模型====>Activity

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

带空间的自动完成文本视图 的相关文章