2013-03-29 17 views
0

我在styles.xml定義的自定義按鈕樣式:如何從代碼中應用按鈕樣式?

<style name="buttonBlack"> 
    <item name="android:background">@drawable/selector_button_black_bg</item> 
    <item name="android:textColor">@android:color/white</item> 
</style> 

當我把它通過佈局XML,它工作正常:

<Button style="@style/buttonBlack" ... /> 

當我把它通過代碼,它不工作(我得到空按鈕,沒有背景):

Button button = new Button(this, null, R.style.buttonBlack); 

我在做什麼錯在這裏?

這裏選擇:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_pressed="true" android:drawable="@drawable/button_black_pressed" /> 
    <item android:state_focused="true" android:drawable="@drawable/button_black_focused" /> 
    <item android:drawable="@drawable/button_black_normal" /> 
</selector> 
+0

它的作品對我來說,你可以發表你的選擇文件? – RobinHood

+0

羅賓,這是爲你工作?什麼Android版本和SDK? – Dusan

回答

0

您應該使用ContextThemeWrapper

Button button = new Button(new ContextThemeWrapper(context, R.style.buttonBlack));