Search code examples
androidandroid-fragmentsbottomnavigationview

Switch between Fragments in BottomNavigationView


I'm working with a simple app with Bottom Navigation View. I have 3 fragments (layout and java). I have BottonNavigationView, declared in my MainActivity.java. My bottonnavigation have 3 items, for the 3 fragments. So, in my MainActivity.java, when i select a item, it start one fragment. So, when i select again another item, nothing happens, because in the java fragment i need to declare the BottonNavigationView, but i don't know how to set it to switch the actual fragment with another fragment. I tried this link, but no success: https://developer.android.com/training/basics/fragments/fragment-ui.html

Sorry my bad english

Here the codes:

Main Activity

 @Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    Fragment selectedFragment = null;
    switch (item.getItemId()) {
        case R.id.navigation_home:
            selectedFragment = HomeFragment.newInstance();
            break;
        case R.id.navigation_dashboard:
            selectedFragment = DashboardFragment.newInstance();
            break;
        case R.id.navigation_notifications:
            selectedFragment = NotificationsFragment.newInstance();
            break;
    }
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.content, selectedFragment);
    transaction.commit();
    return true;
}

Fragment Java Example

public class HomeFragment extends Fragment {
public static HomeFragment newInstance() {
HomeFragment fragment = new HomeFragment();
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.navigation_home, container, false);
return inflater.inflate(R.layout.navigation_home, container, false);
}

Solution

  • You can try it:

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Fragment selectedFragment = null;
        switch (item.getItemId()) {
            case R.id.navigation_home:
                selectedFragment = HomeFragment.newInstance();
                break;
            case R.id.navigation_dashboard:
                selectedFragment = DashboardFragment.newInstance();
                break;
            case R.id.navigation_notifications:
                selectedFragment = NotificationsFragment.newInstance();
                break;
        }
        getSupportFragmentManager().beginTransaction().replace(R.id.content, selectedFragment).commit();
        return true;
    }