2012-11-02 49 views
1

在自定義視圖中,我可以從AttributeSet中獲取自定義attrs值(如下所示)。但是,我如何獲得Android屬性?例如,我如何訪問android:background或android:text? android.R.styleable是不允許的。從AttributeSet獲取Android樣式屬性

<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"); 
+0

不能確定,但​​是如果你使用的 「android.R.attr.text」 或 「android.R.attr.background」,而不是「INT xmlRes = ATTRS。 getAttributeResourceValue(xmlns,「background」,-1)「? – nfirex

回答

9

我想我們會用這個去:

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

如果你不使用硬編碼文本,而是使用字符串引用,那麼使用文本將返回id而不是文本。 – for3st

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; 
       ... 
      } 
+0

不幸的是,「com.android.internal.R.styleable。*」資源是隱藏的,所以不能在Android源代碼之外使用。我使用了類似user123321給出的答案。 – Kasium