How to dynamically create a button and assign it the style defined in styles.xml?

I need to dynamically create a stylized button. I thought maybe I should do it like this:

XmlPullParser parser = m_context.getResources().getXml(R.style.Button_Plain);
buttonStyle = Xml.asAttributeSet(parser);
Button btn = new Button (m_context, buttonStyle);

But it getXmlthrows an exception "The resource request did not work because it is complex." Is there an easy way to do what I need?

+5
source share
2 answers

Use the following constructor to create the Button object:

http://developer.android.com/reference/android/widget/Button.html#Button(android.content.Context , android.util.AttributeSet, int)

public Button (Context context, AttributeSet attrs, int defStyle)

and pass the following parameters:

Button btn = new Button (m_context, null, R.style.Button_Plain);

No need to use XmlPullParser.

+7
source

Mainly:

Button button = new Button(ContextActivity, null, R.style.whateverStyleYouHad);

0
source

All Articles