首页 > 解决方案 > 以编程方式更改 BottomNavigationView 文本大小

问题描述

我在我的 android 应用程序中得到了一个,我在这个答案之后BottomNavigationView设置了自定义文本大小。

<dimen name="design_bottom_navigation_text_size" tools:override="true">25sp</dimen>
<dimen name="design_bottom_navigation_active_text_size" tools:override="true">22sp</dimen>

现在因为我在这个应用程序中实现了多种语言,我需要以BottomNavigationView编程方式更改文本大小。但是由于我使用尺寸设置字体大小的方式,我现在无法弄清楚如何通过代码更改它。

标签: androidbottomnavigationview

解决方案


您可以使用此方法:

private void setBottomNavigationLabelsTextSize(BottomNavigationView bottomNavigationView, float ratio) {
    for (int i = 0; i < bottomNavigationView.getChildCount(); i++) {
        View item = bottomNavigationView.getChildAt(i);

        if (item instanceof BottomNavigationMenuView) {
            BottomNavigationMenuView menu = (BottomNavigationMenuView) item;

            for (int j = 0; j < menu.getChildCount(); j++) {
                View menuItem = menu.getChildAt(j);

                View small = menuItem.findViewById(android.support.design.R.id.smallLabel);
                if (small instanceof TextView) {
                    float size = ((TextView) small).getTextSize();
                    ((TextView) small).setTextSize(TypedValue.COMPLEX_UNIT_PX, ratio * size);
                }
                View large = menuItem.findViewById(android.support.design.R.id.largeLabel);
                if (large instanceof TextView) {
                    float size = ((TextView) large).getTextSize();
                    ((TextView) large).setTextSize(TypedValue.COMPLEX_UNIT_PX, ratio * size);
                }
            }
        }
    }
}

像这样称呼它:

setBottomNavigationLabelsTextSize(bottomNavigationView, 2.0f);

将标签中的文本大小加倍。


推荐阅读