【问题标题】:Change BottomNavigationView text size programmatically以编程方式更改 BottomNavigationView 文本大小
【发布时间】:2020-02-06 21:48:16
【问题描述】:
我在我的 Android 应用程序中有一个 BottomNavigationView,我设置了自定义文本大小 following this answer。
<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 的文本大小。但是由于我使用dimens设置字体大小的方式,我现在无法弄清楚如何通过代码更改它。
【问题讨论】:
标签:
android
bottomnavigationview
【解决方案1】:
你可以使用这个方法:
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);
将标签中的文本大小加倍。