问题
I have created an app with a bottom navigation fragment which consists of 5 main fragments and one extra sub fragment (login Fragment). the thing is I want this login fragment to be replaced with the userAccount fragment once user has logged in successfully.
Note: I am running the App statically at first so I am using a variable Boolean Called Status to check whether user has logged in or not
private static final boolean Status = false;
final Fragment f1 = new HomeFragment();
final Fragment f2 = new SearchFragment();
final Fragment f3 = new CameraFragment();
final Fragment f4 = new ChatFragment();
final Fragment f5 = new AccountFragment();
// logginFragment page should be replaced with AccountFragment once user logged in successfully
final Fragment f6 = new logginFragment();
private BottomNavigationViewEx.OnNavigationItemSelectedListener navListener =
new BottomNavigationViewEx.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
fm.beginTransaction().hide(active).show(f1).commit();
active = f1;
return true;
case R.id.nav_search:
fm.beginTransaction().hide(active).show(f2).commit();
active = f2;
return true;
case R.id.nav_camera:
fm.beginTransaction().hide(active).show(f3).commit();
active = f3;
return true;
case R.id.nav_chat:
fm.beginTransaction().hide(active).show(f4).commit();
active = f4;
return true;
case R.id.nav_account:
fm.beginTransaction().hide(active).show(f5).commit();
active = f5;
return true;
}
/* \getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();*/
return false;
}
};
回答1:
Your Code changes the fragment only when one of the Bottom Navigation Bar item is selected. You can replace the login fragment with account fragment when the login is successful(i.e when button is tapped) and set it to active rather than listening for the change in selection. Let me know if this helps.
void login()
{
if(Successful)
{
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_login,R.id.fragment_account)
.commit();
}
}
来源:https://stackoverflow.com/questions/57245531/bottomnavigationview-fragment-replacement-with-sub-fragment