Android ColorStateList的基本使用

ColorStateList

参考:https://blog.csdn.net/zjh_1110120/article/details/89438309

ColorStateList(颜色状态列表)是一个可以定义在 XML 布局文件中,并最终根据 ColorStateList 应用的 View 的状态显示不同颜色的对象。

文件位置:res/color/filename.xml

应用方式:

  1. In Java: R.color.filename
  2. In XML: @[package:]color/filename

语法:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:color="hex_color"
        android:state_pressed=["true" | "false"]
        android:state_focused=["true" | "false"]
        android:state_selected=["true" | "false"]
        android:state_checkable=["true" | "false"]
        android:state_checked=["true" | "false"]
        android:state_enabled=["true" | "false"]
        android:state_window_focused=["true" | "false"] />
</selector>
属性 定义 取值范围
color 不同状态的颜色值 十六进制的颜色值。可以是如下格式: #RGB #ARGB #RRGGBB #AARRGGBB
state_pressed View 按下的状态 true,false。true,按下;false,认状态,即没有按下之前的状态。
state_selected View 选中的状态 true,false。true,选中;false,未选中。

查看Color state list resource

示例:

//1. text_color_state_list.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/green_700" android:state_pressed="true" />
    <item android:color="@color/grey_700" android:state_pressed="false" />
    <!--认项-->
    <item android:color="@color/grey_700" />
</selector>

注意:

1.ColorStateList 中定义的认 Item 一定要放在最下面

2.ColorStateList 是不能用于 View 的 Background

3.StateListDrawable 是不能用于 TextView 系的 TextColor

代码控制:

private void initView(){
    
        mAlphaB = findViewById(R.id.alphabet_b);
        ColorStateList colorStateList = createColorStateList(getResources().getColor(R.color.green_700), getResources().getColor(R.color.grey_700));
        mAlphaB.setTextColor(colorStateList);
        
    }

    private ColorStateList createColorStateList(int pressed, int normal) {
        //状态
        int[][] states = new int[2][];
        //按下
        states[0] = new int[] {android.R.attr.state_pressed};
        //
        states[1] = new int[] {};
        
        //状态对应颜色值(按下,认)
        int[] colors = new int[] { pressed, normal};
        ColorStateList colorList = new ColorStateList(states, colors);
        return colorList;
    }

相关文章

显卡天梯图2024最新版,显卡是电脑进行图形处理的重要设备,...
初始化电脑时出现问题怎么办,可以使用win系统的安装介质,连...
todesk远程开机怎么设置,两台电脑要在同一局域网内,然后需...
油猴谷歌插件怎么安装,可以通过谷歌应用商店进行安装,需要...
虚拟内存这个名词想必很多人都听说过,我们在使用电脑的时候...