使用了 BottomNavigationView 来做底部导航栏,用来切换 Fragment,可是点击的时候 Fragment 切换了,底部的图标颜色却没有改变,主界面布局文件
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.BottomNavigationView
android:id="@+id/bottomnavigationbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:menu="@menu/bottom_menu"
app:itemIconTint="@color/item_active_color"
app:itemTextColor="@color/item_active_color" />
</android.support.constraint.ConstraintLayout>
首先以为没有设置好 app:itemIconTint、app:itemTextColor 等属性,设置好了之后发现也只是默认第一个选中的图标颜色改变,其他的点击了依然不会改变
后来才发现在监听 BottomNavigationView 菜单项点击的时候没有返回值,设置好返回值,点击的时候图标颜色也就会改变了
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
int itemId = menuItem.getItemId();
switch (itemId){
case R.id.one:{
// ...
return true;
}
case R.id.two:{
// ...
return true;
}
case R.id.three:{
// ...
return true;
}
}
return false;
}
});
判断好每个 ID 的点击事件后,都返回一个 true,这样就能在点击的时候改变导航栏上图标的颜色了,return true 表示这一项被选中了