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

Android底部导航栏选中时图标上移问题求助

解决BottomNavigationView选中时图标上移的问题

你设置stateListAnimator = null后仍出现图标上移,是因为这个动画来自BottomNavigationView的Shift模式(当菜单项数量超过3个时的默认行为:选中项图标上移、显示文字,未选中项图标下移、隐藏文字),而非stateListAnimator控制的属性动画。可以通过以下方案解决:

方案1:关闭Shift模式

通过反射禁用Shift模式,让所有菜单项保持统一的图标位置和显示状态:

fun disableShiftMode(bottomNavigationView: BottomNavigationView) {
    val menuView = bottomNavigationView.getChildAt(0) as BottomNavigationMenuView
    try {
        val shiftingModeField = menuView::class.java.getDeclaredField("mShiftingMode")
        shiftingModeField.isAccessible = true
        shiftingModeField.setBoolean(menuView, false)
        shiftingModeField.isAccessible = false
        
        for (i in 0 until menuView.childCount) {
            val itemView = menuView.getChildAt(i) as BottomNavigationItemView
            itemView.setShifting(false)
            // 刷新选中状态,确保图标位置一致
            itemView.setChecked(itemView.itemData.isChecked)
        }
    } catch (e: NoSuchFieldException) {
        e.printStackTrace()
    } catch (e: IllegalAccessException) {
        e.printStackTrace()
    }
}

调用方式:

val bottomNavigation = findViewById<BottomNavigationView>(R.id.nav_footer)
disableShiftMode(bottomNavigation)

方案2:设置LabelVisibilityMode

通过强制所有菜单项始终显示/隐藏标签,绕过Shift模式的位移逻辑:

// 始终显示标签,图标位置保持一致
bottomNavigation.labelVisibilityMode = BottomNavigationView.LABEL_VISIBILITY_LABELED

// 或者始终隐藏标签,同样避免位移
// bottomNavigation.labelVisibilityMode = BottomNavigationView.LABEL_VISIBILITY_UNLABELED

方案3:自定义菜单项布局

完全自定义每个项的布局,脱离系统默认动画逻辑:

  1. 创建自定义布局layout_bottom_nav_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:paddingVertical="8dp">

    <ImageView
        android:id="@+id/nav_icon"
        android:layout_width="24dp"
        android:layout_height="24dp"/>

    <TextView
        android:id="@+id/nav_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="12sp"
        android:visibility="gone"/>
</LinearLayout>
  1. 在菜单文件中指定该布局:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/home"
        android:title="@string/home"
        android:icon="@drawable/home_white"
        app:itemLayout="@layout/layout_bottom_nav_item"/>
    <!-- 其他菜单项重复上述配置 -->
</menu>
  1. 在代码中手动控制图标切换(直接操作自定义布局中的ImageView)。

额外提示

你当前手动切换图标的逻辑是可行的,只需配合上述任一方案禁用Shift模式的位移动画,即可解决图标上移问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 08:35:06