且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android:可以在可绘制选择器中使用字符串/枚举吗?

更新时间:2023-11-07 20:40:28

第一季度:

打开StateListDrawable.java的源代码时,您可以在读取可绘制xml选择器的inflate方法中看到以下代码: https://android. googlesource.com/platform/frameworks/base/+/refs/heads/master/graphics/java/android/graphics/drawable/StateListDrawable.java

When you open the source-code of StateListDrawable.java, you can see this piece of code in the inflate method that reads the drawable xml selector: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/graphics/java/android/graphics/drawable/StateListDrawable.java

        ...

        for (i = 0; i < numAttrs; i++) {
            final int stateResId = attrs.getAttributeNameResource(i);
            if (stateResId == 0) break;
            if (stateResId == com.android.internal.R.attr.drawable) {
                drawableRes = attrs.getAttributeResourceValue(i, 0);
            } else {
                states[j++] = attrs.getAttributeBooleanValue(i, false)
                        ? stateResId
                        : -stateResId;
            }
        }
        ...

attrs<selector>中每个<item>元素的属性.

attrs are the attributes of each <item> element in the <selector>.

在此for循环中,它获取android:drawable,各种android:state_xxxx和自定义app:xxxx属性.除了android:drawable属性之外的所有属性似乎都只解释为布尔值:调用了attrs.getAttributeBooleanValue(....).

In this for-loop it gets the android:drawable, the various android:state_xxxx and custom app:xxxx attributes. All but the android:drawable attributes seem to be interpreted as booleans only: attrs.getAttributeBooleanValue(....) is called.

我认为这是答案,基于源代码:

I think this is the answer, based on the source code:

您只能向XML添加自定义布尔属性,而不能添加任何其他类型(包括枚举).

You can only add custom boolean attributes to your xml, not any other type (including enums).

第二季度:

我不确定为什么仅将状态专门设置为true才合并状态.我怀疑代码应该看起来像这样:

I'm not sure why the state is merged only if it is specifically set to true. I would suspect the code should have looked like this instead:

private static final int[] MAKE_DARK_BG_SET     = {  R.attr.make_dark_background };
private static final int[] NOT_MAKE_DARK_BG_SET = { -R.attr.make_dark_background };
....
....
@Override
protected int[] onCreateDrawableState(int extraSpace) {
    Log.i(TAG, "onCreateDrawableState()");
    final int[] drawableState = super.onCreateDrawableState(extraSpace + 2);
    mergeDrawableStates(drawableState, mMakeDarkBg? MAKE_DARK_BG_SET : NOT_MAKE_DARK_BG_SET);
    //mergeDrawableStates(drawableState, STR_ATTR_ID);
    return drawableState;
}