6

I need to dynamically create a styled 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 getXml throws exception "Requesting resource failed because it is complex". Is there any easy way to do what I need?

Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335
  • How we add styles progrmatically? http://stackoverflow.com/q/11507476/1012284 – Padma Kumar Jul 25 '12 at 11:47
  • Does this question solve your problem? [Set Style in Code][1] [1]: http://stackoverflow.com/questions/2016249/how-to-programmatically-setting-style-attribute-in-a-view – banzai86 Jul 25 '12 at 11:57

2 Answers2

8

Use Following Constructor to create 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 following parameters:

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

No need to use XmlPullParser.

jeet
  • 29,001
  • 6
  • 52
  • 53
  • Thank you! That page you've linked is the first place I looked, but it seems to lack descriptions for constructors. – Violet Giraffe Jul 25 '12 at 12:08
  • you are welcome, yes, there is a no description at all for button class, but if you will look into View class Documentation, you will find enough. – jeet Jul 25 '12 at 12:10
0

Its basically this:

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

Onur-Andros Ozbek
  • 2,998
  • 2
  • 29
  • 78