【问题标题】:BottomNavigationView set selected item background color programmaticallyBottomNavigationView 以编程方式设置所选项目的背景颜色
【发布时间】:2020-07-28 12:08:52
【问题描述】:

我知道我们可以通过this 方式从 XML 中设置底部导航选择颜色

但我想知道如何通过我的 Activity 以编程方式更改它?

这是我在 Activity 的OnNavigationItemSelectedListener 中尝试的。

 item.getIcon().setTint(ContextCompat.getColor(context, R.color.colorBrown));

还尝试像这样更改色调列表:

item.setIconTintList(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.colorPrimaryBlue)));

这是我的代码的完整 sn-p:

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = item -> {
        switch (item.getItemId()) {
            case R.id.navigationTask:
                    item.getIcon().setTint(ContextCompat.getColor(context, R.color.colorBrown));
                fragment = new MyTaskFragment();
                break;
            case R.id.navigationProfile:
                    item.setIconTintList(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.colorPrimaryBlue)));
                fragment = new ProfileFragment();
                break;
            case R.id.navigationRequest:
                fragment = new RequestListFragment();
                break;
            case R.id.navigationMore:
                fragment = new MoreFragment();
                break;
        }
        loadFragment(fragment);
        return true;
    };

但这对我不起作用。任何有关如何以编程方式更改此设置的想法或参考链接都会对我有所帮助。

注意:我只想更改所选项目的图标和文本色调颜色。不是底部导航中的全部项目。

提前致谢。

【问题讨论】:

    标签: android android-bottomnav


    【解决方案1】:

    你可以使用:

    bottomNavigationView.setItemIconTintList(....)
    

    并使用选择器(不是单一颜色):

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:alpha="1.0" android:color="@color/..." android:state_checked="true"/> 
      <item android:alpha="0.6" android:color="@color/..."/>
    </selector>
    

    如果您想以编程方式进行:

        int[][] states = new int[][] {
            new int[] { android.R.attr.state_checked}, // state_checked
            new int[] { }  // 
        };
    
        int[] colors = new int[] {
            color,
            color2
        };
    
        ColorStateList myColorList = new ColorStateList(states, colors);
        bottomNavigationView.setItemIconTintList(myColorList);
    

    【讨论】:

    • 我试过了,但它影响了底部导航中的所有项目。我只想更改选中的那个。
    • @SnehaMudhigonda 发生这种情况是因为您没有使用选择器。
    • 是的,我用过,但如何以编程方式更改这些可绘制颜色?
    • @SnehaMudhigonda 在这种情况下,您必须以编程方式构建 ColorStateList。检查更新的答案。
    • 文字颜色使用setItemTextColor,图标使用setItemIconTintList
    猜你喜欢
    • 2017-10-23
    • 2021-10-18
    • 2014-06-24
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    相关资源
    最近更新 更多