我通过导航栏进行了一项活动,在其中我通过按动内容(片段)来切换它们。问题在于,每次执行此操作时,我都会刷新片段,而无法在切换之前看到内容。这是我的代码:
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.bbn_item1:
onResume();
if(isNetworkAvailable()){
fragment = new HomeFragment();
}else {
fragment= new NetworkNotAvailable();
}
currentIndex=0;
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.pull_in_left,R.anim.push_out_right);
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
return true;
case R.id.bbn_item2:
if(isNetworkAvailable()){
fragment = new PopularFragment();
}else {
fragment= new NetworkNotAvailable();
}
try{
if(currentIndex < 1 ){
FragmentTransaction transactionb = getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.pull_in_right,R.anim.push_out_left);
transactionb.replace(R.id.fragment_container, fragment);
transactionb.addToBackStack(null);
transactionb.commit();
currentIndex=1;
}else if (currentIndex > 1){
FragmentTransaction transactionb = getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.pull_in_left,R.anim.push_out_right);
transactionb.replace(R.id.fragment_container, fragment);
transactionb.addToBackStack(null);
transactionb.commit();
currentIndex=1;
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
case R.id.bbn_item3:
if(isNetworkAvailable()){
fragment = new PlayingFragment();
}else {
fragment= new NetworkNotAvailable();
}
currentIndex=2;
FragmentTransaction transactionc = getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.pull_in_right,R.anim.push_out_left);
transactionc.replace(R.id.fragment_container, fragment);
transactionc.addToBackStack(null);
transactionc.commit();
return true;
}
return false;
}
};
在我的活动中,我已经实现了onResume()方法,但是当我打开该片段时,它似乎立即被调用(它作为onCreate()工作)
我通过保存每个片段的实例并将其作为参数通过活动筛选器而不是通用的“ new Fragment()”来解决。