1

I have followed this tutorial below but for the life of me can't ever get it to load starting in the favorites fragment (Middle icon on bottomnavigationview).

I have tried everything and looked everywhere.

My app will always load up the favorite text, but the bottomnavigationview will always have the home icon highlighted until I select an icon.

How can I fix this where I can get the app to open and display the favorite fragment while the favorites icon is highlighted and in a null state?

https://codinginflow.com/code-examples/android/bottomnavigationview

Nerdy Bunz
  • 6,040
  • 10
  • 41
  • 100
nyjxrb30
  • 78
  • 1
  • 3
  • 11

1 Answers1

1

In your MainActivity, replace this:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
        bottomNav.setOnNavigationItemSelectedListener(navListener);

        //I added this if statement to keep the selected fragment when rotating the device
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new HomeFragment()).commit();
        }
    }

with this:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
        bottomNav.setOnNavigationItemSelectedListener(navListener);

        //I added this if statement to keep the selected fragment when rotating the device
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new HomeFragment()).commit();
        }

        bottomNav.setSelectedItemId(R.id.nav_favorites);
    }

We're basically just adding this line to the end of the onCreate() function:

bottomNav.setSelectedItemId(R.id.nav_favorites);
Nerdy Bunz
  • 6,040
  • 10
  • 41
  • 100