假设我有一个 DashboadFragment,它有自己的名为 DashboadViewModel
的 ViewModel
。我为 AutoCompleteTextView
创建了单独的布局,它包含在 fragment_dashboard.xml
文件中。我为 AutoCompleteTextView
创建了单独的 ViewModel
,即 AutoCompleteTextViewViewModel
。因此,我在这里尝试观察在 AutoCompleteTextView
中输入到 DashboardFragment
中的数据,但没有成功。
我最近开始使用 MVVM 模式进行开发。
最佳答案
您可以使用委托(delegate) viewModels 在 Fragment 之间传递数据
private val viewModel: ListViewModel by viewModels({requireParentFragment()})
这确实意味着您将在 dashboardFragment 中拥有一个 AutoCompleteTextViewViewModel。
另一种解决方案是使用 setFragmentResult()
API
参见 https://developer.android.com/guide/fragments/communicate#share_data_between_a_parent_and_child_fragment 和 https://developer.android.com/guide/fragments/communicate#fragment-result了解更多信息
关于android-fragments - 如何在 Android 的单个片段中使用多个 View 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59194880/