如何动态创建一个按钮并为其指定styles.xml中定义的样式?

Vio*_*ffe 5 user-interface android

我需要动态创建一个样式按钮.我想也许我应该这样做:

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

getXml抛出异常"请求资源失败,因为它很复杂".有什么简单的方法可以做我需要的吗?

jee*_*eet 7

使用以下构造函数创建Button对象:

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)
Run Code Online (Sandbox Code Playgroud)

并传递以下参数:

Button btn = new Button (m_context, null, R.style.Button_Plain);
Run Code Online (Sandbox Code Playgroud)

无需使用XmlPullParser.