如何更改在Android Studio底部导航栏中选择的图标颜色

时间:2018-07-29 11:41:18

标签: android bottomnavigationview

当我在android studio的底部导航栏中选择一个项目时,所选的背景项目等于values-> colors.xml中的primarycolor。现在我要更改与原色不同的颜色我该如何更改?

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {
        Fragment fragment;
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    fragment = new HomeFragment();
                    loadFragment(fragment);
                    return true;
                case R.id.navigation_addpost:
                    fragment = new AddFragment();
                    loadFragment(fragment);
                    return true;
                case R.id.navigation_notifications:
//                    mTextMessage.setText(R.string.title_notifications);
                    return true;
                case R.id.navigation_profile:
                    fragment = new ProfileFragment();
                    loadFragment(fragment);
                    return true;
            }
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        loadFragment(new HomeFragment());
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        navigation.setItemTextColor(ColorStateList.valueOf(Color.RED));
    }

4 个答案:

答案 0 :(得分:8)

尽管阅读了所有答案,但我对整个过程感到困惑,所以我将逐步解释我是如何解决这个问题的,以便初学者能够正确地理解它

假设您现在创建了名称为 MainActivity 的底部导航 Activity

使用此代码在您的 bottom_navigation_selector.xml 文件夹中创建 drawable

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_checked="true" android:color="@color/yourSelectedColor" />
  <item android:color="@color/defaultColor"  />
</selector>

然后转到 activity_main.xml 布局并将此行添加到 BottomNavigationView

app:itemIconTint="@drawable/bottom_navigation_selector"

如果您还想相应地更改文本颜色,则还需要添加此行

app:itemTextColor="@drawable/bottom_navigation_selector"
    

答案 1 :(得分:4)

要在BottomNavigationView中更改所选标签图标的颜色,应使用选择器。

创建bottom_navigation_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:color="@color/yourSelectedColor" />
<item android:color="@color/defaultColor"  />
</selector>

app:itemIconTint="@drawable/bottom_navigation_selector"应用于xml文件中的BottomNavigationView。

答案 2 :(得分:0)

尝试

iface=

更新:

navigation.setItemIconTintList(Color.BLUE);

答案 3 :(得分:0)

bottomNavigationView.setItemIconTintList(ColorStateList.valueOf(Color.parseColor("#3F51B5")));