2011-05-08 56 views
5

我创建活动中的一个按钮:如何扩展按钮的样式?

Button contactButton = new Button(this, null, R.style.ContactButton); 
contactButton.setText(contactName); 
contactsView.addView(contactButton); 

与相应的风格:

<style name="ContactButton" parent="@android:style/Widget.Button"> 
</style> 

我试图得到它使用的ContactButton风格,延伸Widget.Button风格,这样我就可以将样式属性保留在一个地方而不必重新定义整个按钮(9-patch background等)。

但是我无法找到任何方法来继承默认的按钮样式。上面的结果总是显示为默认的TextView。

我所得到的是通过按钮样式到按钮的构造,这给我回默认按钮的外观,但我当然不能覆盖这种方式最接近:

Button contactButton = new Button(this, null, android.R.attr.buttonStyle); 

因此,任何想法如何完成这个?

更新:

这似乎是一个bug in the View class,这就解释了为什么new Button(this, null, android.R.attr.buttonStyle)作品和new Button(this, null, android.R.style.Widget_Button)没有,虽然前者只是后者的参考。

我只是遇到了这个bug,因为我以编程方式创建按钮,在XML中设置style属性正常。

我还想知道是否有一个简单的解决方法,它仍然允许我使用样式系统。

+0

您是否尝试过从XML扩展按钮而不是实用地创建它? – schwiz 2011-05-09 00:55:32

+0

您是否找到解决方案? – 2015-08-25 21:25:51

回答

-1

您可以创建一个工厂类并让它返回一个重新定义的对象的新实例吗?

Class ButtonFactory(){ 
    public Button getStyledButton(String name){ 
     Button styledButton = new Button(); 
     styledButton.setText(name); 
     // do stuff to button 
     return styledButton 
    } 
} 

将此信息添加到您的活动中。

onCreate(..){ 
    ButtonFactory builder = new ButtonFactory(); 
    Button styledButton = builder.getStyledButton(); 
} 
+0

是直接修改按钮实例确实有效,但我希望使用样式系统来保持它很好地分离。 – Anotherdroid 2011-05-08 23:05:38