2013-11-21 119 views
1

我有一個自定義的android視圖類,其中包括將大量文本直接繪製到提供給其onDraw覆蓋的畫布中。自定義視圖中的Android屬性

我想要做的是有一個屬性,可以設置爲「?android:attr/textAppearanceLarge」類似的東西,並選擇常規文本設置,無需進一步的樣式。

在我的自定義視圖的attrs.xml,我有

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="MyView" > 
     ... 

     <attr name="textAppearance" format="reference" /> 

     ... 
    </declare-styleable> 
</resources> 

,然後在CustomView.java

final int[] bogus = new int[] { android.R.attr.textColor, android.R.attr.textSize, android.R.attr.typeface, android.R.attr.textStyle, android.R.attr.fontFamily }; 
final int ap = styledAttributes.getResourceId(com.test.R.styleable.MyView_textAppearance, -1); 
final TypedArray textAppearance = ap != -1 ? context.obtainStyledAttributes(ap, bogus) : null; 

if (textAppearance != null) { 
    for (int i = 0; i < textAppearance.getIndexCount(); i++) { 
     int attr = textAppearance.getIndex(i); 

     switch (attr) { 
     case android.R.attr.textColor: textColor = textAppearance.getColor(attr, textColor); break; 
     case android.R.attr.textSize: textSize = textAppearance.getDimensionPixelSize(attr, textSize); break; 
     case android.R.attr.typeface: typefaceIndex = textAppearance.getInt(attr, typefaceIndex); break; 
     case android.R.attr.textStyle: textStyle = textAppearance.getInt(attr, textStyle); break; 
     case android.R.attr.fontFamily: fontFamily = textAppearance.getString(attr); break;   
     } 
    } 

    textAppearance.recycle(); 
} 

我已經試過了各種的開關變量的變化,對案件常量等,我永遠不會得到任何即使遠程有用的東西 。

我在這裏做錯了什麼?

回答

0

我想你訪問到不同的資源:

com.test.R.styleable.MyView_textAppearance 

是你自己的,

android.R.attr.textColor 

等是Android的。

所以我設法使它定義自己的特性:

<com.test.TextView 
     android:id="@+id/textView" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     myns:textColor="@android:color/darker_gray" 
     myns:textSize="18sp" 
     myns:textStyle="normal"/> 

和attrs.xml:

<declare-styleable name="MyView_textAppearance"> 
    <attr name="textColor" format="reference|color" /> 

    <attr name="textSize" format="dimension" /> 
    <attr name="textStyle"> 
     <flag name="normal" value="0" /> 
     <flag name="bold" value="1" /> 
     <flag name="italic" value="2" /> 
    </attr> 

</declare-styleable> 
相關問題