获取Java代码中的自定义属性的值

mic*_*ael 3 android

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

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Custom">
        <attr name="src" format="integer" />
    </declare-styleable>
</resource>
Run Code Online (Sandbox Code Playgroud)

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

有用。我从布局xml文件获取“ src”的值。但是我的问题是,为什么android在R类中不生成值,所以我不需要在Java代码中再次使用字符串'src'?

Ric*_*ler 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();
}
Run Code Online (Sandbox Code Playgroud)