我正在添加一个 LiveData 来表示一个状态。这是 ViewModel 类:
public class MyViewModel extends AndroidViewModel {
// Create a LiveData with a Status
private MutableLiveData<Integer> status;
public TsViewModel(@NonNull Application application) {
super(application);
}
public MutableLiveData<Integer> getCurrentStatus() {
if (status == null) {
status = new MutableLiveData<Integer>();
}
return status;
}
void setCurrentStatus(int stat) {
status.setValue(stat);
}
}
当前状态在本机代码中设置。我希望在自定义应用程序类中更新此状态。但似乎我无法从该类中获得 viewModel:
public class MyApplication extends Application {
public static Context context;
public void onCreate() {
super.onCreate();
MyApplication .context = getApplicationContext();
model = new ViewModelProvider(this).get(MyViewModel.class); /* <---- this fails */
}
}
这个想法实际上是尽可能早地设置此状态,并且任何观察者都会知道。我怎样才能做到这一点?