Android - 如何通过编程在LinearLayout中设置按钮样式?

52

我正在通过编程方式创建一个带有一些按钮的AlertDialog的LinearLayout。

希望做到这一点:

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

但是像这样的代码:

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");

我该如何在程序中设置按钮的样式(使用按钮栏)?


很遗憾,这是不可能的。您只能通过编程将样式添加到文本跨度。 - Tomasz Gawel
可能这个能帮到你:https://dev59.com/mHI-5IYBdhLWcg3wF0Uc - 0gravity
不工作 - user1365315
6个回答

56

这对我有用:

int buttonStyle = R.style.your_button_style;
Button button = new Button(new ContextThemeWrapper(context, buttonStyle), null, buttonStyle)

55

希望我来得不算太晚 :)

嗯,样式可以在初始化阶段应用于一个 View。例如:

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

1
这仅适用于API级别11及以上,你不知道如何在旧的API中实现吗? - Oliv
6
我相信对于旧的 API 来说这是不可能的。然而,作为一种替代方案,我建议您将您的 LinearLayout 定义为一个 XML,并在代码中使用 inflate 将该 XML 填充到对象中,以达到您想要的所有样式效果。 - waqaslam
1
如果我将“Button”更改为“LinearLayout”,那么我将失去Button类的其他方法,例如setText()。 - ishandutta2007
15
对我不起作用。因此,按钮没有任何样式,看起来像是平面文本。 - Konstantin Konopko

18

这个回答是唯一真正解决我问题的:http://belencruz.com/2013/04/set-styles-programmatically-in-android/

基本上,创建一个只包含你想要样式的<Button/>元素的布局XML文件。然后,以编程方式填充它并自定义按钮文本。

以下是一个示例:

<?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");

2
这对我来说不会改变风格。 - Elliptica
谢谢!显然这是唯一可行的解决方案。使用ContextThemeWrapper或在Button构造函数中指定样式并不能应用所有属性。 - JCarlosR

10

来自AirBnB的Paris库非常适合此类场景,可以像这样进行编程配置:

Paris.styleBuilder(textView)
        .add(R.style.MyGreenTextView)
        .textSizeRes(R.dimen.my_text_size_small)
        .apply();

5

与其使用waqaslams,

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

(根据评论,这是依赖于API的) 我还阅读了来自此处的ridoys答案 [Android Button Styling Programatically] ,这是

transferBtn.setBackgroundResource(R.layout.buttonstyle);

(根据您使用的API版本,上述答案中的任何一个也可能适用于您),但这是对我有效的解决方法(注意从“layout”更改为“drawable”):
Button b = new Button(this);
b.setBackgroundResource(R.drawable.button_custom_green);

(来自[如何在视图中以编程方式设置样式属性]的答案)


3

当我将样式传递到Button构造函数中时,我的情况是样式根本没有加载。

似乎是因为我正在使用Material Design视图。以下是解决我的方法:

val themeWrapper = ContextThemeWrapper(
      context,
      R.style.AppTheme_ButtonPrimary // my button style
)

val button = MaterialButton(themeWrapper)

请注意,MaterialButton已经代替了Button
我在这里找到了解决方案:如何在Android中以编程方式指定视图的样式

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接