开发者

How do I extend the style of a button?

开发者 https://www.devze.com 2023-03-04 17:13 出处:网络
I\'m creating a button in an activity: Button contactButton = new Button(this, null, R.style.ContactButton);

I'm creating a button in an activity:

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

With the corresponding style:

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

I'm trying to get it to use the ContactButton style, extending the Widget.Button style, so that I can keep style properties in one place without having to redefine the whole button (9-patch background et al.)

However I cannot find any way for it to inherit the default button style. The result of the above always appears to be a default TextView.

The closest I've got is passing buttonStyle into the Button constructor, which gives me back the 开发者_开发问答default button look but of course I can't override it this way:

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

So, any ideas how to accomplish this?

Update:

This seems to be a bug in the View class, which explains why new Button(this, null, android.R.attr.buttonStyle) works and new Button(this, null, android.R.style.Widget_Button) doesn't, although the former is just a reference to the latter.

I'm only running into this bug because I'm creating the Buttons programmatically, setting the style attribute in XML works fine.

I'd still like to know if there's a simple workaround which still lets me use the style system.


Can you create a factory class and have it return you new instances of a redefined object?

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

Add this in Your activity.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号