如何在不每次重新创建片段的情况下在片段之间切换?
How to switch between fragments without recreating fragments each time?
使用 bottomNavigationView 在片段之间切换时,每次按下按钮时都会重新创建片段。
这是我的代码:
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentguest, fragment)
.commit();
return true;
}
return false;
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.eventsguest:
fragment = new Events();
break;
case R.id.about_usguest:
fragment = new About_Us();
break;
}
return loadFragment(fragment);
}
不要每次都创建片段 (fragment = new Events();
) 您可以在对象字段中保留片段的引用,并在 onNavigationItemSelected
方法中保留 return 已经创建的片段。
或者您可以将 ViewPager
与 BottomNavigationView
结合使用。参考这个 article and if you do not know much about ViewPager. Refer this.
替换方法会破坏您的片段。一种解决方法是将它们设置为 Visibility.GONE,另一种(不太容易)的方法是将它们保存在一个变量中。如果这样做,请确保您不会左右泄漏内存。
meredrica in here回答了这个问题
使用 bottomNavigationView 在片段之间切换时,每次按下按钮时都会重新创建片段。
这是我的代码:
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentguest, fragment)
.commit();
return true;
}
return false;
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.eventsguest:
fragment = new Events();
break;
case R.id.about_usguest:
fragment = new About_Us();
break;
}
return loadFragment(fragment);
}
不要每次都创建片段 (fragment = new Events();
) 您可以在对象字段中保留片段的引用,并在 onNavigationItemSelected
方法中保留 return 已经创建的片段。
或者您可以将 ViewPager
与 BottomNavigationView
结合使用。参考这个 article and if you do not know much about ViewPager. Refer this.
替换方法会破坏您的片段。一种解决方法是将它们设置为 Visibility.GONE,另一种(不太容易)的方法是将它们保存在一个变量中。如果这样做,请确保您不会左右泄漏内存。
meredrica in here回答了这个问题