2012-07-10 121 views
31

我使用一些按钮以编程方式为AlertDialog创建LinearLayout。Android - 如何以编程方式设置Linearlayout中的按钮样式?

WANT做到这一点:

<LinearLayout android:id="@+id/footer" android:layout_width="fill_parent" 
style="@android:style/ButtonBar"> 

但随着这样的代码:programmitically

LinearLayout buttons = new LinearLayout(parentContext); 
buttons.setOrientation(LinearLayout.HORIZONTAL); 
LinearLayout.LayoutParams buttonsParams = 
    new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 
    LayoutParams.WRAP_CONTENT); 
topLayout.addView(buttons, buttonsParams); 
buttons.setLayoutParams(buttonsParams); 
Button btnAdd = new Button(context); 
btnAdd.setText("Add"); 

我如何设置按钮的样式(使用一个按钮栏)?

+0

不幸的是它是不可能的。您只能以编程方式向文本范围添加样式。 – 2012-07-10 21:28:42

+0

也许这可能有所帮助:http://stackoverflow.com/questions/2016249/how-to-programmatically-setting-style-attribute-in-a-view – 0gravity 2012-07-10 21:29:25

+0

不工作 http://stackoverflow.com/ questions/3142067/android-set-style-in-code – user1365315 2013-03-14 01:59:43

回答

41

希望我不是太晚了入党:)

好,样式可以在初始化阶段被应用到View。例如:

LinearLayout button = new LinearLayout(context, null, android.R.style.ButtonBar); 
+1

这只适用于API Level 11,难道你不知道如何在旧API中做到这一点? – Oliv 2013-04-22 12:46:37

+6

@Oliv我相信它不适用于较旧的API。但是,作为替代方案,我建议您将“LinearLayout”定义为具有所需样式的XML,并简单地**将该XML扩充到代码中的对象。 – waqaslam 2013-04-22 14:30:23

+0

如果我将'Button'更改为'LinearLayout',则我放弃Button类中的其他方法,如setText() – ishandutta2007 2017-10-01 05:12:08

2

相反waqaslams

LinearLayout button = new LinearLayout(context, null, android.R.style.ButtonBar); 

(这是由评论来看,API可靠的)我也看过ridoys从这里 回答[Android Button Styling Programatically]这是

transferBtn.setBackgroundResource(R.layout.buttonstyle); 

(公开以上答案,因为其中的一个也可能适用于您,取决于您使用的API版本),

但是,这是我什么工作(介意 “布局” 变更为 “绘制”)

Button b = new Button(this); 
b.setBackgroundResource(R.drawable.button_custom_green); 

(答案从[How to programmatically setting style attribute in a view

20

这为我工作

Button button = new Button(new ContextThemeWrapper(context,ButtonStyle), null, ButtonStyle) 
+0

int ButtonStyle = R.style.your_button_style; – 2017-12-22 19:43:22

4

这是实际交付什么,我一直在寻找的唯一答案:http://belencruz.com/2013/04/set-styles-programmatically-in-android/

基本上,创建一个布局XML文件,只需要一个<Button/>元素和所需的样式。然后,以编程方式膨胀它,并自定义按钮文本。

东西线沿线的:

<?xml version="1.0" encoding="utf-8"?> 
<Button style="@style/your_custom_style_here"/> 

在代码:

Button button = (Button)getLayoutInflater().inflate(R.layout.your_custom_button_layout_file, null); 
button.setText("Your Text"); 
相关问题