java - 如何在底部导航栏中选择任何其他按钮而不是默认情况下的第一个按钮
问题描述
我正在创建包含带有 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:
提前致谢。
解决方案
将此行添加到您的代码中
mainbottomNav.setSelectedItemId(R.id.bottom_action_account);
推荐阅读
- flutter - 主题数据中的原色不起作用
- python - 删除反向键的方法:python map dict中的值对?
- postgresql - 在 PostgreSQL 中存储 UUID 的最佳数据类型是什么?
- linux - 多个显示器有时会停止在 RHEL8 桌面上工作
- python - 此“水平剖面”图的名称以及如何在 PyPlot 中实现
- c# - 仅在调用 ThrowIfCancellationRequested 时取消任务
- python - matplotlib scatter Valueerror: 'c' 参数有 n 个元素,不能与大小为 m 的 'x' 和 'y' 一起使用
- python - SUMO GUI 和 TraCI 问题:无法使用端口 xxxxx 连接到 TraCI 服务器(TraCI 服务器已经完成)
- anova - 如何对重复测量进行探索性分析?
- python - IndexError: tuple index out of range when I try to create an executable from a python script using auto-py-to-exe