android 如何以编程方式创建ColorStateList?

lymnna71  于 2022-12-25  发布在  Android
关注(0)|答案(8)|浏览(227)

我尝试使用以下代码通过编程创建一个ColorStateList

ColorStateList stateList = new ColorStateList(states, colors);

但我不确定这两个参数是什么。
根据文件:

public ColorStateList (int[][] states, int[] colors)

在API级别1中添加
创建返回从状态到颜色的指定Map的ColorStateList。
有人能给我解释一下怎么做这个吗?
状态的二维数组的含义是什么?

qlfbtfca

qlfbtfca1#

有关http://developer.android.com/reference/android/R.attr.html#state_above_anchor可用状态的列表,请参见www.example.com。
如果您想设置禁用、未聚焦、未选中等状态的颜色,只需取消这些状态:

int[][] states = new int[][] {
    new int[] { android.R.attr.state_enabled}, // enabled
    new int[] {-android.R.attr.state_enabled}, // disabled
    new int[] {-android.R.attr.state_checked}, // unchecked
    new int[] { android.R.attr.state_pressed}  // pressed
};

int[] colors = new int[] {
    Color.BLACK,
    Color.RED,
    Color.GREEN,
    Color.BLUE
};

ColorStateList myList = new ColorStateList(states, colors);
mzaanser

mzaanser2#

有时这就足够了:

int colorInt = getResources().getColor(R.color.ColorVerificaLunes);
ColorStateList csl = ColorStateList.valueOf(colorInt);
wvt8vs2t

wvt8vs2t3#

第一个维度是状态集的数组,第二个维度是状态集本身。colors数组列出了每个匹配状态集的颜色,因此colors数组的长度必须与states数组的第一个维度匹配(否则当状态被“使用”时,它将崩溃)。下面是示例:

ColorStateList myColorStateList = new ColorStateList(
    new int[][] {
        new int[] {
                android.R.attr.state_pressed
            }, //1
            new int[] {
                android.R.attr.state_focused
            }, //2
            new int[] {
                android.R.attr.state_focused, android.R.attr.state_pressed
            } //3
    },
    new int[] {
        Color.RED, //1
            Color.GREEN, //2
            Color.BLUE //3
    }
);

编辑示例:XML颜色状态列表,如:

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

会是这个样子

ColorStateList myColorStateList = new ColorStateList(
        new int[][]{
                new int[]{android.R.attr.state_pressed},
                new int[]{}
        },
        new int[] {
                context.getResources().getColor(R.color.white),
                context.getResources().getColor(R.color.black)
        }
);
a14dhokn

a14dhokn4#

下面是一个如何在Kotlin中以编程方式创建ColorList的示例:

val colorList = ColorStateList(
        arrayOf(
                intArrayOf(-android.R.attr.state_enabled),  // Disabled
                intArrayOf(android.R.attr.state_enabled)    // Enabled
        ),
        intArrayOf(
                Color.BLACK,     // The color for the Disabled state
                Color.RED        // The color for the Enabled state
        )
)
0s7z1bwu

0s7z1bwu5#

不幸的是,没有一个解决方案对我有效。
1.如果你不设置按下状态在第一次它不会检测到它。
1.如果您设置了它,那么您需要定义空状态来添加默认颜色

ColorStateList themeColorStateList = new ColorStateList(
        new int[][]{
                new int[]{android.R.attr.state_pressed},
                new int[]{android.R.attr.state_enabled},
                new int[]{android.R.attr.state_focused, android.R.attr.state_pressed},
                new int[]{-android.R.attr.state_enabled},
                new int[]{} // this should be empty to make default color as we want
        },
        new int[]{
                pressedFontColor,
                defaultFontColor,
                pressedFontColor,
                disabledFontColor,
                defaultFontColor
        }
);

这是源代码中的构造函数:

/**
 * Creates a ColorStateList that returns the specified mapping from
 * states to colors.
 */
public ColorStateList(int[][] states, int[] colors) {
    mStateSpecs = states;
    mColors = colors;

    if (states.length > 0) {
        mDefaultColor = colors[0];

        for (int i = 0; i < states.length; i++) {
            if (states[i].length == 0) {
                mDefaultColor = colors[i];
            }
        }
    }
}
uemypmqf

uemypmqf6#

借鉴answer by Jonathan Ellis,在Kotlin中可以定义一个helper函数,使代码更符合习惯,更容易阅读,因此可以编写如下代码:

val colorList = colorStateListOf(
    intArrayOf(-android.R.attr.state_enabled) to Color.BLACK,
    intArrayOf(android.R.attr.state_enabled) to Color.RED,
)

colorStateListOf可以这样实现:

fun colorStateListOf(vararg mapping: Pair<IntArray, Int>): ColorStateList {
    val (states, colors) = mapping.unzip()
    return ColorStateList(states.toTypedArray(), colors.toIntArray())
}

我还有:

fun colorStateListOf(@ColorInt color: Int): ColorStateList {
    return ColorStateList.valueOf(color)
}

这样我就可以调用相同的函数名,不管它是选择器还是单色。

gorkyyrv

gorkyyrv7#

我创建ColorStateList的构建器类

private class ColorStateListBuilder {
    List<Integer> colors = new ArrayList<>();
    List<int[]> states = new ArrayList<>();

    public ColorStateListBuilder addState(int[] state, int color) {
        states.add(state);
        colors.add(color);
        return this;
    }

    public ColorStateList build() {
        return new ColorStateList(convertToTwoDimensionalIntArray(states),
                convertToIntArray(colors));
    }

    private int[][] convertToTwoDimensionalIntArray(List<int[]> integers) {
        int[][] result = new int[integers.size()][1];
        Iterator<int[]> iterator = integers.iterator();
        for (int i = 0; iterator.hasNext(); i++) {
            result[i] = iterator.next();
        }
        return result;
    }

    private int[] convertToIntArray(List<Integer> integers) {
        int[] result = new int[integers.size()];
        Iterator<Integer> iterator = integers.iterator();
        for (int i = 0; iterator.hasNext(); i++) {
            result[i] = iterator.next();
        }
        return result;
    }
}

示例使用

ColorStateListBuilder builder = new ColorStateListBuilder();
builder.addState(new int[] { android.R.attr.state_pressed }, ContextCompat.getColor(this, colorRes))
       .addState(new int[] { android.R.attr.state_selected }, Color.GREEN)
       .addState(..., some color);

if(// some condition){
      builder.addState(..., some color);
}
builder.addState(new int[] {}, colorNormal); // must add default state at last of all state

ColorStateList stateList = builder.build(); // ColorStateList created here

// textView.setTextColor(stateList);
hyrbngr7

hyrbngr78#

如果您使用Colors.xml资源

int[] colors = new int[] {
                getResources().getColor(R.color.ColorVerificaLunes),
                getResources().getColor(R.color.ColorVerificaMartes),
                getResources().getColor(R.color.ColorVerificaMiercoles),
                getResources().getColor(R.color.ColorVerificaJueves),
                getResources().getColor(R.color.ColorVerificaViernes)

        };

ColorStateList csl = new ColorStateList(new int[][]{new int[0]}, new int[]{colors[0]}); 

    example.setBackgroundTintList(csl);

相关问题