Violet Giraffe Violet Giraffe -4 years ago 42
Android Question

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

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

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

throws exception "Requesting resource failed because it is complex". Is there any easy way to do what I need?

Answer Source

Use Following Constructor to create Button Object:, android.util.AttributeSet, int)

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

and pass following parameters:

Button btn = new Button (m_context, null,;

No need to use XmlPullParser.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download