Android ViewModel无法在片段更改后继续存在
作者:互联网
我一直在尝试使用viewmodel和livedata来分享片段之间的信息.
但是当我从第一个片段更改为另一个片段时,我的viewmodel似乎重新初始化,使我丢失了以前存储的所有数据.
我在我的片段中以相同的方式获得了两次我的viewmodel:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
interventionViewModel = ViewModelProviders.of(this).get(InterventionsViewModel.class);
}
这就是我在我的活动中替换我的framgents的方式(我猜问题必须来自片段生命周期,但我无法弄清楚错误在哪里:/)
public void showFragment(Fragment fragment) {
String TAG = fragment.getClass().getSimpleName();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment, TAG);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commitAllowingStateLoss();
}
public void backstackFragment() {
Log.d("Stack count", getSupportFragmentManager().getBackStackEntryCount() + "");
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
finish();
}
getSupportFragmentManager().popBackStack();
removeCurrentFragment();
}
private void removeCurrentFragment() {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
Fragment currentFrag = getSupportFragmentManager()
.findFragmentById(R.id.fragment_container);
if (currentFrag != null) {
transaction.remove(currentFrag);
}
transaction.commitAllowingStateLoss();
}
当我需要一个片段时,我调用backStackFragment()删除当前片段,然后调用showFragment(MyFragment.newInstance());
该片段是AndroidStudio生成的片段
谢谢你的帮助,
亲切,
马蒂厄
解决方法:
尝试绑定到活动而不是当前片段.
interventionViewModel = ViewModelProviders.of(activity).get(InterventionsViewModel.class);
标签:android,android-fragments,android-viewmodel,android-livedata,architecture-compon 来源: https://codeday.me/bug/20190727/1550075.html