2012-03-01 64 views
1

這是我的問題。我已經定義了自定義主題和樣式,以便在相關的.xml文件中自定義各種視圖。下面是一些代碼提取物:Android - 使用屬性來調整自定義樣式

的themes.xml:

... 
<style name="Legacy" parent="android:Theme.NoTitleBar"> 
    <item name="android:buttonStyle">@style/Legacy.Button</item> 
    ... 
</style> 

styles.xml:

... 
<style name="Legacy.Button" parent="@android:style/Widget.Button"> 
    <item name="android:textColor">#ffffff</item> 
    <item name="android:background">@drawable/button_selector_blue</item> 
    <item name="android:textSize">15dp</item> 
</style> 

比方說,我把我的應用程序的主題遺產。如果我在佈局中使用Button,它將得到我自定義的默認參數(白色文本,背景爲@ drawable/button_selector_blue等)。

現在讓我們說,我想保持這些參數保存的文本大小:我想有一個更大的文本大小,這將在titleSize屬性在attrs.xml定義一些按鈕:

... 
<attr name="titleSize" format="reference|dimension" /> 

以及在我的themes.xml文件中爲每個主題設置了哪個值。

所以我的佈局將包含類似:

<Button 
    android:id="@+idmyButtonId" 
    android:drawableRight="@drawable/aDrawable" 
    android:text="@string/someText" 
    android:textSize="?titleSize" 
    android:layout_width="fill_parent" android:layout_height="wrap_content"> 
</Button> 

當啓動我的應用程序,我得到以下錯誤: java.lang.UnsupportedOperationException:無法轉換爲維度:類型= 0X2

所以看起來我不能使用屬性調整自定義樣式 - 至少不是這樣。這樣的事情可能嗎?如果不是,你會用什麼來達到這樣的結果?

我想給用戶在不同主題中進行選擇的能力,所以我不能只是定義一個額外的ButtonWithLargeText樣式,並直接在我的佈局中使用它。

感謝您的幫助!

+0

我做類似的東西在這裏! ! http://stackoverflow.com/questions/17103894/overriding-referenced-style-attributes – toobsco42 2013-06-14 08:10:12

回答

0

我終於得到它的工作。我沒有在attrs.xml中定義標題的大小,而是使用了dimens.xml。所以,現在的以下工作:

<Button 
    android:id="@+idmyButtonId" 
    android:drawableRight="@drawable/aDrawable" 
    android:text="@string/someText" 
    android:textSize="@dimen/titleSize" 
    android:layout_width="fill_parent" android:layout_height="wrap_content"> 
</Button> 

雖然我把我的常規文本大小的按鈕,通過使用這個(這是我在我的styles.xml定義):

<Button 
    android:id="@+id/idRegularButton" 
    android:text="@string/regularSizeText" 
    android:layout_width="wrap_content" android:layout_height="wrap_content"> 
</Button>