以编程方式获取可设置属性的名称

时间:2014-04-28 17:36:17

标签: android attributes

有没有办法以编程方式获取可设置属性的名称:

<declare-styleable name="TextView">
    <attr name="DataContext" format="string" />
    <attr name="Text" format="string" />
</declare-styleable>

例如,我想从"Text"整数值获得R.styleable.TextView_Text

1 个答案:

答案 0 :(得分:2)

你的风格是:

<declare-styleable name="TextView">
    <attr name="DataContext" format="string" />
    <attr name="Text" format="string" />
</declare-styleable>

使用此功能调用它:

custom:DataContext="@string/xxxx"

在您的代码中:

TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.TextView);


  int n = a.getIndexCount();
    for (int i = 0; i < n; i++) {
        int attr = a.getIndex(i);
        switch (attr) {
        case R.styleable.TextView_DataContext:
            title = a.getString(attr);
            break;

        case R.styleable.TextVie_Text:
            //Any you want
            break;
        default:
            Log.d("TAG", "Unknown attribute for " + getClass().toString() + ": " + attr);
            break;
        }
    }

    a.recycle();