3

我在 attrs.xml 文件中创建一个属性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Custom">
        <attr name="src" format="integer" />
    </declare-styleable>
</resource>

在我的代码中,我得到这样的属性值: attrs.getAttributeIntValue("mynamespace", "src", -1);

有用。我从布局 xml 文件中获取 'src' 的值。但我的问题是为什么 android 不会在 R 类中生成一个值,这样我就不需要在我的 java 代码中再次使用字符串 'src' 了?

4

1 回答 1

5

而是使用TypedArray

public CustomView(final Context context) {
    this(context, null);
}

public CustomView(final Context context,
            final AttributeSet attrs) {
    this(context, attrs, 0);
}

public CustomView(final Context context,
            final AttributeSet attrs, final int defStyle) {
        super(context, attrs, defStyle);

    final TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.Custom, defStyle, 0);

    int src = a.getInt(R.styleable.Custom_src, 0);

    a.recycle();
}
于 2012-04-13T04:48:11.880 回答