首页 > 解决方案 > 如何在底部导航栏中选择任何其他按钮而不是默认情况下的第一个按钮

问题描述

我正在创建包含带有 4 个按钮的底部导航栏的 android 应用程序。我想在最初启动应用程序时预选第三个按钮,而不是默认选择的第一个选项卡。我已经使用 replace frgment 最初使用以下代码加载第三个片段

secondFragment = new second();
        replaceFragment(secondFragment);

但是,虽然第三个片段成功加载,但默认情况下第一个选项卡而不是第三个选项卡是活动的

这是菜单中的 xml 文件

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item

        android:id="@+id/bottom_action_home"
        android:icon="@drawable/ic_visibility_black_24dp"
        android:title="I"
        app:showAsAction="always|withText" />
    <item
        android:id="@+id/bottom_action_notif"
        android:icon="@drawable/ic_visibility_black_24dp"
        android:title="II"
        android:checked="true"
        app:showAsAction="always|withText" />
    <item
        android:id="@+id/bottom_action_account"
        android:icon="@drawable/ic_visibility_black_24dp"
        android:title="III"
        app:showAsAction="always|withText"/>

    <item
        android:id="@+id/bottom_action_chat"
        android:icon="@drawable/ic_visibility_black_24dp"
        android:title="IV"
        app:showAsAction="always|withText"/>
</menu>

和活动 xml 文件是

       <android.support.design.widget.BottomNavigationView
            android:id="@+id/mainBottomNav"
            android:background="@color/colorblog"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:menu="@menu/bottom_menu"
            android:layout_alignParentBottom="true"/>

我的java文件是

  mainbottomNav = findViewById(R.id.mainBottomNav);
        BottomNavigationViewHelper.removeShiftMode(mainbottomNav);//disable BottomNavigationView shift mode
        // FRAGMENTS
        mainbottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                switch (item.getItemId()){

                    case R.id.bottom_action_home:
                        
                        return true;

                    case R.id.bottom_action_notif:
                        
                        return true;


                    case R.id.bottom_action_account:
                        
                        return true;



                    case R.id.bottom_action_chat:
                      
                    default:
                        return false;


                }
            }
        });

我想在应用程序启动时激活第三个按钮,即case R.id.bottom_action_account:

提前致谢。

标签: javaandroidandroid-layout

解决方案


将此行添加到您的代码中

  mainbottomNav.setSelectedItemId(R.id.bottom_action_account);

推荐阅读