2013-05-09 42 views
0

我試圖在有人單擊某個按鈕時更改按鈕的樣式。我想將背景改爲文字顏色。但是,只有文本顏色發生了變化。從這我得出結論的樣式是已更改,但由於某些原因背景不能被覆蓋。更改樣式只能部分工作:文本顏色更改,背景不更改

我使用這個代碼在onclick處理程序:

Button send_button = (Button) findViewById(R.id.button1); 
send_button.setTextAppearance(context, R.style.activeButtonTheme); 

我styles.xml相關風格:

<style name="buttonTheme"> 
    <item name="android:background">@color/white</item> 
    <item name="android:textColor">@color/orange</item> 
    <item name="android:paddingTop">6dp</item> 
    <item name="android:paddingBottom">6dp</item> 
    <item name="android:layout_margin">2dp</item> 
</style> 

<style name="activeButtonTheme" parent="@style/buttonTheme"> 
    <item name="android:background">@color/orange</item> 
    <item name="android:textColor">@color/white</item> 
</style> 

這裏有什麼問題嗎?

我不想從Java設置背景顏色,我只想改變Java中的樣式。

+0

確保您的java代碼中不存在對'setBackground'的調用。 – 2013-05-09 09:18:32

+0

@AdamArold除了這個和alertDialog之外沒有任何東西。 – Keelan 2013-05-09 09:19:15

回答

1

爲此目的使用selector。在佈局

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:drawable="@drawable/drawable_for_dissabled_button" android:state_enabled="false"/> 
    <item android:drawable="@drawable/drawable_for_pressed_button" android:state_enabled="true" android:state_pressed="true"/> 
    <item android:drawable="@drawable/drawable_for_enabled_button" android:state_enabled="true" android:state_focused="true"/> 
    <item android:drawable="@drawable/drawable_for_enabled_button" android:state_enabled="true"/> 
</selector> 

分配剛剛創建選擇器按鈕:檢查this link的細節(自定義背景部分)關於你的代碼,在你的資源目錄中確定適當的 selector.xml文件,類似的東西文件:

<Button android:id="@+id/your_button_id" 
    android:background="@drawable/selector" /> 
+0

謝謝!這工作。你能否說我爲什麼試過不行? 「背景」屬性有什麼特別之處嗎? – Keelan 2013-05-09 10:43:13

+0

據我所知,創建視圖後不支持更改樣式。 – Eugene 2013-05-09 10:47:42

+0

這不能解釋爲什麼文本顏色改變;這是所有這一切的奇怪之處。 – Keelan 2013-05-09 10:48:13