You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过代码设置BottomNavigationView的未选中状态图标?

如何通过代码为BottomNavigationView设置未选中状态图标

当然可以实现,下面提供两种常用的方法:

方法一:使用StateListDrawable(推荐,符合系统默认逻辑)

通过创建包含选中/未选中状态的Drawable,设置给MenuItem后,系统会自动根据选中状态切换图标:

// 准备选中和未选中的Drawable对象
Drawable selectedDrawable = getResources().getDrawable(R.drawable.icon_selected, null);
Drawable unselectedDrawable = getResources().getDrawable(R.drawable.icon_unselected, null);

// 创建状态列表Drawable
StateListDrawable stateDrawable = new StateListDrawable();
// 添加未选中状态(-android.R.attr.state_checked 表示未选中)
stateDrawable.addState(new int[]{-android.R.attr.state_checked}, unselectedDrawable);
// 添加选中状态
stateDrawable.addState(new int[]{android.R.attr.state_checked}, selectedDrawable);

// 应用到目标MenuItem
bottomNavigationView.getMenu().findItem(R.id.tab1).setIcon(stateDrawable);

方法二:直接操作BottomNavigationItemView(适合动态修改)

如果需要在运行时动态修改已设置的未选中图标,可以直接获取对应的ItemView进行设置:

// 获取BottomNavigationMenuView
BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomNavigationView.getChildAt(0);
// 找到对应位置的BottomNavigationItemView(注意:位置对应菜单的顺序,从0开始)
BottomNavigationItemView itemView = (BottomNavigationItemView) menuView.getChildAt(0);

// 设置未选中图标
itemView.setIcon(unselectedDrawable);
// 可选:重新设置选中状态图标
itemView.setSelectedIcon(selectedDrawable);

注意:方法二中的子View位置需要和菜单中Item的顺序对应,如果菜单Item顺序有变化,需要调整索引值。

内容的提问来源于stack exchange,提问作者Micro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 18:12:05