为 BottomNavigationView 中的导航项添加边距

Add margins to navigation item in BottomNavigationView

我有一个 BottomNavigationView 实例化如下:

BottomNavigationView navigationView = findViewById(R.id.bottom_navigation);
navigationView.setOnNavigationItemSelectedListener(this);

/menu/menu.xml 看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/first_id"
        android:icon="@drawable/home_icon"
        android:title="Item" />

    <item
        android:id="@+id/second_id"
        android:icon="@drawable/home_icon"
        android:title="Item" />

    <item
        android:id="@+id/third_id"
        android:icon="@drawable/home_icon"
        android:title="Item" />

    <item
        android:id="@+id/fourth_id"
        android:icon="@drawable/home_icon"
        android:title="Item" />
</menu>

而 /drawable/home_icon 看起来像这样:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportHeight="24.0"
    android:viewportWidth="24.0">
    <path
        android:fillColor="#FFFFF0"
        android:pathData="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"
        android:strokeColor="#FFFFF0"
        android:strokeWidth="1" />
</vector>

如您所见,我在导航项的按钮周围设置了边框,但是,边框相互接触。因此我想在菜单按钮之间添加边距。我该怎么做?

正如您从屏幕截图中也可以看到的那样,我正在阻止换档模式。我通过调用

来做到这一点
BottomNavigationViewHelper.removeShiftMode(navigationView);

使用来自 .

的代码

按钮周围的边框已添加如下:

int stateListDrawable = drawableStateLists.get(currentFragment);
navigationView.setItemBackgroundResource(stateListDrawable);

stateListDrawable 指的是 StateListDrawable,当按下不同的菜单按钮时它会发生变化。 StateListDrawable 指的是一个 xml 选择器,它又指的是一个像这样的 xml 形状,例如:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="5dp"/>
    <stroke
        android:width="2dp"
        android:color="@color/intro"/>
</shape>

在仔细检查和试验来源之后,我想出了最基本和合法的解决方案 - 插入可绘制对象本身。

像这样声明 xml 可绘制对象:

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetLeft="10dp"
    android:insetRight="10dp">
    <shape android:shape="rectangle">
        <corners android:radius="5dp" />
        <stroke
            android:width="2dp"
            android:color="#ffffff" />
    </shape>
</inset>

您将获得以下输出:

我首先努力寻找一个程序化的解决方案,但事实证明并不存在那么多的接缝来做到这一点(至少这是我的发现)。准确地说,每个项目的布局参数都是 ViewGroup.LayoutParams 的实例。如果项目以 ViewGroup.MarginLayoutParams 布局,则可以单独为每个项目设置边距。在此之前,背景可绘制对象 xml 应该改为应用插图。