2013-03-29 21 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));