我一直在尝试使用viewmodel和livedata来分享片段之间的信息.
但是当我从第一个片段更改为另一个片段时,我的viewmodel似乎重新初始化,使我丢失了以前存储的所有数据.
我在我的片段中以相同的方式获得了两次我的viewmodel:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
interventionViewModel = ViewModelProviders.of(this).get(InterventionsViewModel.class);
}
Run Code Online (Sandbox Code Playgroud)
这就是我在我的活动中替换我的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();
}
Run Code Online (Sandbox Code Playgroud)
当我需要一个片段时,我会调用backStackFragment()
删除当前片段然后调用showFragment(MyFragment.newInstance());
该片段是AndroidStudio生成的片段 …
android android-fragments android-livedata android-viewmodel android-architecture-components
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_shuffle"
android:icon="@drawable/rand"
android:orderInCategory="1"
android:showAction="always"
android:title="shuffle"/>
<item
android:id="@+id/action_end"
android:icon="@drawable/end"
android:orderInCategory="2"
android:showAction="always"
android:title="End"/>
</menu>
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.action_shuffle:
//shuffle
break;
case R.id.action_end:
stopService(playIntent);
musicSrv=null;
System.exit(0);
break;
}
return super.onOptionsItemSelected(item);
}
Run Code Online (Sandbox Code Playgroud)
我为这件事彻夜难眠。我已经尽了一切努力,但这让我感到非常头疼。
起初是 uri 未注册错误,但在我验证错误后,现在读取如下:
错误:外部资源http://schemas.android.com/apk/res/android未注册。
我如何注册这个?
错误#2
错误:(2, 66) cvc-elt.1.a: 找不到“菜单”元素的声明
错误:文件过早结束