删除BottomNavigationView图标和中心标题 [英] Remove BottomNavigationView Icons and center title
问题描述
我有一个包含3个项目的底部导航视图.我只希望每个选项卡的文本居中,因此希望完全删除图标(不仅使它们透明).
I have a bottom navigation view with 3 items. I want to only have centered text for each tab, and would therefore like to fully remove icons (not only make them transparent).
如何删除图标并使标题居中?
How can I remove Icons and center the titles?
这就是我所拥有的:这就是我要的:
This is what I have: This is what I want:
我的代码:(首选XML解决方案)
My code: (Prefer solution in XML)
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_alignParentBottom="true">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/navigationBar"
android:background="@color/navigation"
app:theme="@style/BottomNavigationTheme"
app:menu="@menu/bottom_navigation_menu"
android:minHeight="@dimen/abc_action_bar_default_height_material">
</com.google.android.material.bottomnavigation.BottomNavigationView>
</RelativeLayout>
</merge>
bottom_navigation_menu.xml
bottom_navigation_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/ic_home"
android:title="@string/home">
</item>
<item
android:id="@+id/ic_today"
android:title="@string/today">
</item>
<item
android:id="@+id/ic_you"
android:title="@string/you">
</item>
</menu>
推荐答案
这对我有用
private int baselineHeight = 0;
private void removeIcons(BottomNavigationView view) {
BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView itemView = (BottomNavigationItemView) (menuView.getChildAt(i));
BaselineLayout baseline = (BaselineLayout) itemView.getChildAt(1);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) baseline.getLayoutParams();
baselineHeight = baselineHeight > 0 ? baselineHeight : (menuView.getHeight() + baseline.getHeight()) / 2;
layoutParams.height = baselineHeight;
baseline.setLayoutParams(layoutParams);
}
}
只需在您的Activity中的 onCreate()中对其进行调用,然后将您的 BottomNavigationView 作为参数传递即可.
just call it in onCreate() in your Activity and pass your BottomNavigationView as parameter.
如果您不想用多余的代码弄乱活动"或片段",并且希望它出现在您的布局XML 中,则可以创建一个自定义视图>扩展BottomNavigationView 并在 onLayout()覆盖中调用此函数.
If you don't want to clutter your Activities or Fragments with excess code and you want this present in your layout XML you can create a custom View that extends BottomNavigationView and call this function in onLayout() override.
这篇关于删除BottomNavigationView图标和中心标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!