无法使用 Bottomnavigationview 正确加载片段

2023-12-10

我已经遵循了下面的教程,但我一生都无法让它从收藏夹片段(底部导航视图上的中间图标)开始加载。

我已经尝试了一切并到处寻找。

我的应用程序将始终加载最喜欢的文本,但底部导航视图将始终突出显示主页图标,直到我选择一个图标。

如何解决此问题,让应用程序打开并显示收藏夹片段,同时收藏夹图标突出显示并处于空状态?

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


在您的 MainActivity 中,将其替换为:

@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();
        }
    }

有了这个:

@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);
    }

我们基本上只是将这一行添加到 onCreate() 函数的末尾:

bottomNav.setSelectedItemId(R.id.nav_favorites);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法使用 Bottomnavigationview 正确加载片段 的相关文章

随机推荐