在BottomNavigationView中为导航项添加边距。

8
我有一个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>

如您所见,导航按钮周围有边框,但边框互相贴在一起。因此,我想要在菜单按钮之间添加边距。我该如何做? enter image description here 从截图中可以看出,我正在防止移位模式。我通过调用下面的代码来实现:
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>

你是如何添加这些边框的? - azizbekian
@azizbekian 请查看我的编辑。 - kalabalik
1个回答

9

经过仔细检查和实验,我得出了最基本和合法的解决方案——插入可绘制对象本身。

像这样声明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>

您将获得以下输出:

enter image description here

我努力寻找程序解决方案,但结果发现没有那么多的接缝可以这样做(至少是我的发现)。准确地说,每个项目的布局参数都是ViewGroup.LayoutParams的实例。如果使用ViewGroup.MarginLayoutParams对项目进行布局,则可能会为每个项目单独设置边距。在那之前,应该将背景可绘制xml应用于插入部分。

如何实现这个? - Ghasem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接