I made an activity with a navigation bar, where I switch the content (fragments) by pressing on them. The problem is that every time I do it, I get the fragments refreshed, without being able to see the content before switching from them. This is my code:
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;
}
};
In my activities I already implemented the onResume() method, but it looks like it gets invoked as soon as I open the fragment (it works as a onCreate())
我通过保存每个片段的实例并将其作为参数传递给活动过滤器而不是通用的“new Fragment()”来解决。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.