0

我期待創建一個自定義ViewGroup用於圖書館;其中包含幾個ImageButton對象。我希望能夠應用每種款式ImageButton;但我不知道如何通過編程方式應用樣式,而不是通過將屬性資源應用於參數defStyleAttr;像這樣:默認樣式資源預API級別21

mImageButton = new ImageButton(
     getContext(),     // context 
     null,       // attrs 
     R.attr.customImageButtonStyle); // defStyleAttr 

這樣做的問題是,只有這樣,才能改變每個ImageButton的風格將是在父主題應用樣式到這個屬性。但我希望能夠設置默認樣式,而無需爲使用此庫的每個項目手動設置此屬性。

有一個參數完全符合我的要求; defStyleRes,它可以像這樣使用:

mImageButton = new ImageButton(
     getContext(),     // context 
     null,       // attrs 
     R.attr.customImageButtonStyle, // defStyleAttr 
     R.style.customImageButtonStyle); // defStyleRes 

此參數只適用於API等級21以上,但我的項目目標API等級16以上。那麼如何設置defStyleRes或應用默認樣式,而無需訪問此參數?


我使用ContextThemeWrapper應用我的風格,由@EugenPechanec,這似乎運作良好的建議,但每個ImageButton現在有默認ImageButton背景下,即使我的風格適用<item name="android:background">@null</item>

這裏是我使用的樣式:

<style name="Widget.Custom.Icon" parent="android:Widget"> 
    <item name="android:background">@null</item> 
    <item name="android:minWidth">56dp</item> 
    <item name="android:minHeight">48dp</item> 
    <item name="android:tint">@color/selector_light</item> 
</style> 

而且這是我正在申請它:

ContextThemeWrapper wrapper = new ContextThemeWrapper(getContext(), R.style.Widget_Custom_Icon); 
mImageButton = new AppCompatImageButton(wrapper); 

左邊是什麼,我得到,而右邊的是什麼我想它看起來像:

enter image description hereenter image description here

回答

1

defStyleAttr用於解決來自主題屬性的默認小部件樣式。

例如:AppCompatCheckBox要求R.attr.checkBoxStyle。您的主題定義爲<item name="checkBoxStyle">@style/Widget.AppCompat.CheckBox</item>

如果該屬性未在您的主題中定義,則該小部件將從其defStyleResR.style.Widget_AppCompat_CheckBox

請注意,這些不是widget使用的實際值。

我還沒有看到defStyleRes構造函數參數在框架之外使用。當詢問TypedArray的資源時,所有這些參數(加上默認值)都會被使用。

如何真正解決你的問題

所以在這四個參數的構造函數是不是適用於所有平臺。您需要找到一種方法來提供默認樣式。考慮你想要的樣式應用:

<style name="MyImageButtonStyle" parent=""> ... </style> 

您需要一種方法將其轉換爲一個defStyleAttr參數。定義一個主題覆蓋的默認樣式:

// When creating manually you have to include the AppCompat prefix. 
mImageButton = new AppCompatImageButton(
    new ContextThemeWrapper(getContext(), R.style.MyImageButtonThemeOverlay) 
); 

你並不需要指定任何其他參數AppCompatImageButton意志皮卡:

<style name="MyImageButtonThemeOverlay" parent=""> 
    <!-- AppCompat widgets don't use the android: prefix. --> 
    <item name="imageButtonStyle">@style/MyImageButtonStyle</item> 
</style> 

現在你可以使用這個主題覆蓋創建ImageButton默認爲R.attr.imageButtonStyle


如果看起來哈克在您指定的style="@style/MyImageButtonStyle"屬性你可以隨時充氣您的自定義視圖層次或個人從部件XML。

+0

'ContextThemeWrapper'似乎是正確的選擇。我以前遇到過,但它完全逃脫了我的想法。不幸的是它造成了另一個問題;由於某些原因,它在每個ImageButton上添加一個背景資源。我可以通過設置'mImageButton.setBackgroundResource(0)'來移除背景,但是我不能在我的樣式資源中使用' @ null'這樣做,儘管我可以改變其他的屬性。任何想法可能會導致這一點? – Bryan

+0

@Bryan好吧,發佈在問題結尾處發生了變化的內容,我會研究它。 –

+0

更新了我的新代碼和圖片。 – Bryan