2014-01-24 38 views
1

我在TextView工廠中使用了TextSwitcher。我想將我在TextSwitcher上設置的樣式傳遞給TextViews。TextSwitcher - 獲取樣式屬性並將其傳遞給另一個視圖

TextSwitcher沒有3參數構造函數。

是否可以從屬性集中獲取樣式屬性?

的Xml

<com.my.TextSwitcher 
    style="@style/My.TextView.Style" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" /> 

的Java

public class MyTextSwitcher extends TextSwitcher { 

    public MyTextSwitcher(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     int style = attrs.getAttributeIntValue("", "style", 0); // I tried this to no avail 
     setFactory(new MyTextViewFactory(context, attrs, style)); 
    } 

    private static class MyTextViewFactory implements ViewFactory { 
     private final Context context; 
     private final AttributeSet attrs; 
     private final int style; 

     public MyTextViewFactory(Context context, AttributeSet attrs, int style) { 
      this.context = context; 
      this.attrs = attrs; 
      this.style = style; 
     } 

     @Override 
     public View makeView() { 
      return new TextView(context, attrs, style); 
     } 
    } 
} 

是讓INT我自己的自定義屬性將通過風格是唯一的答案?我不能使用內置的樣式標籤?

+0

'ATTRS。 getStyleAttribute()'? – Luksprog

+1

大聲笑我怎麼錯過了。 *羞愧的臉*是的答案我會打勾。因此'getAttributeResourceValue(null,「style」)'也可以。我在做'intValue' grrr – Blundell

回答

1

可以使用檢索style屬性(並把它傳遞到內視圖):

attrs.getStyleAttribute() 

或其等價物(如文檔提到):

getAttributeResourceValue(null, "style") 
1

一種替代方法是在XML中聲明TextView,但是這會給我可以擁有的子TextView的數量帶來較小的靈活性。

<com.my.TextSwitcher 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"> 

    <TextView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     style="@style/My.TextView.Style" 
     android:text="@string/some_text" /> 

    <TextView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     style="@style/My.TextView.Style" 
     android:text="@string/some_other_text" /> 

    </com.my.TextSwitcher> 
相關問題