Android 将SavedStateHandle与共享视图模型一起使用
我有一个共享的ViewModel,它在我的MainActivity和我的所有片段中共享,因此它基本上是我整个android应用程序的共享数据模型 我基本上在任何地方都可以这样访问它:Android 将SavedStateHandle与共享视图模型一起使用,android,android-fragments,androidx,android-jetpack,android-viewmodel,Android,Android Fragments,Androidx,Android Jetpack,Android Viewmodel,我有一个共享的ViewModel,它在我的MainActivity和我的所有片段中共享,因此它基本上是我整个android应用程序的共享数据模型 我基本上在任何地方都可以这样访问它: viewModel = new ViewModelProvider(this).get(SharedViewModel.class); 现在我想开始使用savedstatehold保存此状态,因此我将以下构造函数添加到我的模型中: public class SharedViewModel extends View
viewModel = new ViewModelProvider(this).get(SharedViewModel.class);
现在我想开始使用savedstatehold
保存此状态,因此我将以下构造函数添加到我的模型中:
public class SharedViewModel extends ViewModel {
public SharedViewModel(SavedStateHandle savedStateHandle) {
this.savedStateHandle = savedStateHandle;
String blah = savedStateHandle.get("blah");
}
每当我更改blah
时,我调用savedStateHandle上的set()
:
public void setBlah(String b) {
blah = b;
savedStateHandle.set("blah", b);
}
构造函数中实际上提供了savedstatehold
:viewModel是用它创建的,但每次我从它获取值时savedstatehold.get(“blah”)
它总是返回null
,即使我在上一次运行应用程序(我从Android Studio启动)时已将值存储在其中
如何在此共享视图模型中保存状态
我的依赖项:
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.navigation:navigation-fragment:2.3.5'
implementation 'androidx.navigation:navigation-ui:2.3.5'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation 'androidx.savedstate:savedstate:1.1.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:2.3.1'