Can't get fragment to load properly with Bottomnavigationview

后端 未结 1 486
盖世英雄少女心
盖世英雄少女心 2021-01-16 13:24

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 ha

相关标签:
1条回答
  • 2021-01-16 13:47

    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);
    
    0 讨论(0)
提交回复
热议问题