2013-11-28 15 views
7

我有一個9patch設置爲我的佈局的背景。不過,我仍然希望通過使用selectableItemBackground attr提供觸摸反饋。?android:attr/selectableItemBackground與另一個現有背景

我試過使用<layer-list>與9patch和selectableItemBackground作爲android:drawable第二個<item>,但是這並不奏效。

我也可以嘗試製作選擇器並覆蓋梯度可繪製的android用於selectableItemBackgroundlist_selector_background_pressed.xml<layer-list>。但在4.4奇巧選擇背景顏色實際是灰色的,而不是在糖豆藍色,所以我真的不能硬編碼:(

必須有一個更簡單的方法,正確的傢伙d:

回答

16

我已經嘗試使用一個與9patch和 selectableItemBackground由於Android:第二的繪製,不過 沒有工作

是,在層列表繪製屬性(或國家列表)一樣。不接受attr值。您將看到一個Resource.NotFoundException。查看LayerDrawable(或StateListDrawable)的源代碼解釋了原因:您提供的值被假定爲drawable的id。

但是,你可以檢索代碼屬性的主題和具體平臺抽拉:

// Attribute array 
int[] attrs = new int[] { android.R.attr.selectableItemBackground }; 

TypedArray a = getTheme().obtainStyledAttributes(attrs); 

// Drawable held by attribute 'selectableItemBackground' is at index '0'   
Drawable d = a.getDrawable(0); 

a.recycle(); 

現在,你可以創建一個LayerDrawable

LayerDrawable ld = new LayerDrawable(new Drawable[] { 

         // Nine Path Drawable 
         getResources().getDrawable(R.drawable.Your_Nine_Path), 

         // Drawable from attribute 
         d }); 

// Set the background to 'ld' 
yourLayoutContainer.setBackground(ld); 

你還需要集yourLayoutContainer's clickable屬性:

android:clickable="true" 
+0

這看起來很有趣。會嘗試。 –

+0

@JasonHu對不起,我沒有完全評論你的評論,正在打電話。如果你有問題,請繼續。 – Vikram

+0

令人驚歎。奇蹟般有效。我最初以爲我必須爲選定的狀態選擇一個選擇器(9patch只在默認情況下,而LayerDrawable在選中時)。但它似乎從selectableItemBackground返回的drawable實際上是選擇器本身。謝謝。 –

相關問題