Android 使用viewModel作为数据绑定变量重用片段/底页
我将举一个例子,以便很容易地解释我的问题 考虑在我的应用程序中使用Android 使用viewModel作为数据绑定变量重用片段/底页,android,mvvm,data-binding,android-viewmodel,Android,Mvvm,Data Binding,Android Viewmodel,我将举一个例子,以便很容易地解释我的问题 考虑在我的应用程序中使用ViewModelA和FragmentB的FragmentA 我有一个BottomSheetSample,用于FragmentA和FragmentB中,因为底部工作表的作用很小,比如选择一个值,我想共享显示底部工作表的片段的ViewModel,而不是使用单独的ViewModel并将数据传输到片段的ViewModel。我正在像这样将ViewModel绑定到导航图 内部FragmentA private val viewModel:
ViewModelA
和FragmentB
的FragmentA
我有一个BottomSheetSample
,用于FragmentA
和FragmentB
中,因为底部工作表的作用很小,比如选择一个值,我想共享显示底部工作表的片段的ViewModel,而不是使用单独的ViewModel并将数据传输到片段的ViewModel
。我正在像这样将ViewModel
绑定到导航图
内部FragmentA
private val viewModel: ViewModelA by navGraphViewModels(R.id.nav_A_graph) { viewModelFactory }
内部BottomSheetSample
private val viewModel: ViewModelA by navGraphViewModels(R.id.nav_A_graph) { viewModelFactory }
我像这样将ViewModel
传递给XML,以便将其用于数据绑定:
val binding: BottomSheetSampleBinding =
DataBindingUtil.inflate(inflater, R.layout.bottomSheet, container, false)
binding.viewModel = viewModel
底页XML示例:
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<variable
name="viewModel"
type="com.ui.fragmenta.ViewModelA" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@{()->viewModel.oneSelected()} />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@{()->viewModel.twoSelected()} />
</LinearLayout>
</layout>
现在,如果我必须在第三个片段中使用相同的底部表单,我必须复制底部表单样本,然后再次执行整个操作。这看起来是多余的,因为一次又一次地复制相同的底部工作表。但我不知道如何避免这样做。有人能告诉我正确的方法吗
希望我能清楚我的问题。创建一个BaseViewModel
(任何名称),并将底部工作表所需的所有内容保留在BaseViewModel
中。在底部图纸中使用此BaseViewModel
<layout>
<data>
<variable
name="viewModel"
type="com.ui.fragmentb.BaseViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@{()->viewModel.oneSelected()}" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@{()->viewModel.twoSelected()}" />
</LinearLayout>
</layout>
使用BaseViewModel
扩展您的ViewModelA
,ViewModelB
,谢谢您的回答。让我试试,然后再回到youThanks Manohar。。我一辈子都搞不明白为什么我没有想到这一点。
<layout>
<data>
<variable
name="viewModel"
type="com.ui.fragmentb.BaseViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@{()->viewModel.oneSelected()}" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@{()->viewModel.twoSelected()}" />
</LinearLayout>
</layout>