项目中使用了ViewPager2+BottomNavigationView的方式布局主页面,在使用过程中,产品经理想让BottomNavigationView在线中Item的时候将文字变成粗体,在网上找了一圈之后好像并没有相应的解决方案,最后自己找了一种解决方案,记录在这,方便自己或有需要的人使用。
override fun setNavigationView(navigationView: BottomNavigationView) {
val menuView = navigationView.getChildAt(0) as BottomNavigationMenuView
val buttons = menuView.javaClass.getDeclaredField("buttons")
buttons.isAccessible = true
val texts = buttons.get(menuView) as Array<BottomNavigationItemView>
texts.forEach {
//获取到选中变大的文字
var largeText = it.javaClass.getDeclaredField("largeLabel")
//获取到正常状态下的文字
// var smallText = it.javaClass.getDeclaredField("smallLabel")
largeText.isAccessible = true
var large = largeText.get(it) as TextView
large.paint.isFakeBoldText = true
largeText.isAccessible = false
}
buttons.isAccessible = false
}
禁用掉BottomNavigationView切换的隐藏icon效果,可以直接使用下边的代码。
bottomNavigation.labelVisibilityMode = LabelVisibilityMode.LABEL_VISIBILITY_LABELED
切换效果有三种模式
public @interface LabelVisibilityMode {
/**
* Label behaves as "labeled" when there are 3 items or less, or "selected" when there are 4 items
* or more.
*/
int LABEL_VISIBILITY_AUTO = -1;
/** 只显示被选中的label */
int LABEL_VISIBILITY_SELECTED = 0;
/** 一直显示label */
int LABEL_VISIBILITY_LABELED = 1;
/** 全部显示 */
int LABEL_VISIBILITY_UNLABELED = 2;
}
我是使用反射获取到对应TextView然后修改其属性,有别的方法请告知