从AttributeSet获取Android样式属性

时间:2012-11-02 22:43:12

标签: android android-layout

在自定义视图中,我可以从AttributeSet获取自定义attrs值(如下所示)。但是我如何获得Android属性?例如,我如何访问android:background或android:text?不允许使用android.R.styleable。

<mine.custom.RangeSeekBar
    custom:selectedMinValue="2"
    custom:selectedMaxValue="4"
    android:background="@drawable/my_skin" />


public RangeSeekBar(Context context, AttributeSet attrs, int defStyle) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RangeSeekBar, defStyle, 0);
    selectedMinValue = a.getInt(R.styleable.RangeSeekBar_selectedMinValue, selectedMinValue);
    selectedMaxValue = a.getInt(R.styleable.RangeSeekBar_selectedMaxValue, selectedMaxValue);
    minRangeValue = a.getInt(R.styleable.RangeSeekBar_minRangeValue, minRangeValue);
    maxRangeValue = a.getInt(R.styleable.RangeSeekBar_maxRangeValue, maxRangeValue);
    a.recycle();
}

编辑:这是标准方式吗?

final String xmlns="http://schemas.android.com/apk/res/android";
    int xmlRes = attrs.getAttributeResourceValue(xmlns, "background", -1);
    String xmlText = attrs.getAttributeValue(xmlns, "text");

2 个答案:

答案 0 :(得分:9)

我想我们会接受这个:

final String xmlns="http://schemas.android.com/apk/res/android";
int xmlRes = attrs.getAttributeResourceValue(xmlns, "background", -1);
String xmlText = attrs.getAttributeValue(xmlns, "text");

答案 1 :(得分:0)

comment所述,这不是规范的做法。此外,这实际上只适用于硬编码字符串。 来自android source code for Preference class的示例可能有所帮助:

  TypedArray a = context.obtainStyledAttributes(attrs,
                 com.android.internal.R.styleable.Preference, defStyle, 0);
         for (int i = a.getIndexCount(); i >= 0; i--) {
             int attr = a.getIndex(i); 
             switch (attr) {
                 ...
                 case com.android.internal.R.styleable.Preference_key:
                     mKey = a.getString(attr);
                     break;
                 ...
             }
相关问题