我正在一个 Activity 中创建一个按钮:
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 补丁背景等)
但是我找不到任何方法让它继承默认按钮样式。上面的结果总是显示为默认的 TextView。
我得到的最接近的方法是将 buttonStyle 传递给 Button 构造函数,这使我恢复了默认按钮外观,但当然我不能以这种方式覆盖它:
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)
不是,尽管前者只是对后者的引用。
我遇到这个错误只是因为我以编程方式创建按钮,在 XML 中设置 style
属性工作正常。
我仍然想知道是否有一个简单的解决方法仍然可以让我使用样式系统。
最佳答案
你能创建一个工厂类并让它返回一个重新定义对象的新实例吗?
Class ButtonFactory(){
public Button getStyledButton(String name){
Button styledButton = new Button();
styledButton.setText(name);
// do stuff to button
return styledButton
}
}
将此添加到您的 Activity 中。
onCreate(..){
ButtonFactory builder = new ButtonFactory();
Button styledButton = builder.getStyledButton();
}
关于android - 如何扩展按钮的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5930945/