我需要实现我的应用程序的UI,就像Instagram那样。我需要使用底部导航视图从不同的片段切换,但我需要保持片段的状态,就像我离开它们一样。我怎样才能做到这一点?
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
item.setChecked(true);
switch (item.getItemId()) {
case R.id.action_formation:
if (homeFragment == null) {
homeFragment = new HomeFragment();
}
displayFragment(homeFragment);
break;
case R.id.action_result:
if (introResultFragment == null) {
introResultFragment = new IntroResultFragment();
}
displayFragment(introResultFragment);
break;
case R.id.action_market:
displayFragment(new MarketFragment());
break;
}
return false;
}
public void displayFragment(final Fragment fragment) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment, fragment.getClass().toString());
fragmentTransaction.commit();
}
答案 0 :(得分:1)
已经有很长时间了,但是我想在github中提供我的开源库,该库实现了Youtube和Instagram的相同UX: https://github.com/ZachBublil/ZNavigator
您必须将此依赖项添加到gradle:
compile 'com.zach.znavigator:znavigator:1.0.0'
您唯一要做的就是在BottomNavigationView中传递您想要的片段列表:
public class SampleActivity extends NavigationActivity {
private BottomNavigationView navigationView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navigationView = (BottomNavigationView) findViewById(R.id.navigationView);
LinkedHashMap<Integer, Fragment> rootFragments = new LinkedHashMap<>();
rootFragments.put(R.id.tab1, new FirstTab());
rootFragments.put(R.id.tab2,new SecondTab());
rootFragments.put(R.id.tab3, new ThirdTab());
init(rootFragments, R.id.container);
navigationView.setOnNavigationItemSelectedListener(this);
navigationView.setOnNavigationItemReselectedListener(this);
}
@Override
public void tabChanged(int id) {
navigationView.getMenu().findItem(id).setChecked(true);
}
}
如果要在其中一个选项卡中打开新片段作为内部屏幕,则可以通过使用选项卡片段中的ZNavigation类来做到这一点:
ZNavigation.openChildFragment(getFragmentManager(),new ChildFragment());
答案 1 :(得分:0)
只需记住活动片段,并使用userVisiableHint在每个片段中获取活动状态。
private Fragment currentFragment; // need to be init
private void switch2Fragment(Fragment target){
getFragmentManager().executePendingTransactions();
if(target.isAdded){
getFragmentManager().beginTransaction().hide(currentFragment).show(target).commit();
} else {
getFragmentManager().beginTransaction().hide(currentFragment).add(R.id.xxx, target).commit();
}
currentFragment.setUserVisibleHint(false);
currentFragment = target;
target.setUserVisibleHint(true);
}
private boolean isFragmentActive(Fragment target){
return target.getUserVisibleHint();
}