Android - 底部导航菜单更改图标图像

时间:2018-02-06 00:18:44

标签: android android-studio icons bottomnavigationview

选中后,我需要更改底部导航标签的图标菜单。我找到了使用item.setIcon(R.drawable.latest_icon_sel_green);选择时更改图像的方法,但是现在我需要在取消选择时更改图像。我怎么能这样做?

navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.navigation_latest:
                        viewPager.setCurrentItem(0);
                        item.setIcon(R.drawable.latest_icon_sel_green);

                        return true;
                    case R.id.navigation_news:
                        viewPager.setCurrentItem(1);
                        item.setIcon(R.drawable.news_icon_sel_green);

                        return true;
                    case R.id.navigation_user:
                        viewPager.setCurrentItem(2);
                        item.setIcon(R.drawable.user_icon_sel_green);

                        return true;
                    case R.id.navigation_upload:
                        viewPager.setCurrentItem(3);
                        item.setIcon(R.drawable.upload_icon_sel_green);

                        return true;
                    case R.id.navigation_share:
                        viewPager.setCurrentItem(4);
                        item.setIcon(R.drawable.share_icon_sel_green);

                        return true;
                }
                return false;
            }
        });

1 个答案:

答案 0 :(得分:0)

只需使用xml创建自定义drawable,如下所示,并为您的导航项目提供选择后无需setIcon,

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:drawable="@drawable/share_icon_sel_green"/>
    <item android:drawable="@drawable/share_icon_unsel_green"/>
</selector>