簡體   English   中英

Android - 如何在 Linearlayout 中以編程方式設置按鈕樣式?

[英]Android - How to programmatically set the button style in a Linearlayout?

我正在以編程方式為帶有一些按鈕的 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");

如何以編程方式設置按鈕的樣式(使用按鈕欄)?

希望我加入派對還不算太晚:)

好吧,樣式可以在初始化階段應用於View 例如:

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

這對我有用:

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

這是實際提供我正在尋找的唯一答案: 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");

AirBnB 的Paris庫非常適合這種情況,允許像這樣進行編程配置:

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

代替瓦卡斯拉姆

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

(來自[ 如何在視圖中以編程方式設置樣式屬性的答案)

在我的情況下,當我將它們傳遞給Button構造函數時,根本沒有加載樣式。 似乎是因為我使用的是材料設計視圖。 這里是什么解決了我的案子:

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

val button = MaterialButton(themeWrapper)

請注意,創建的是MaterialButton而不是Button

我在以下位置找到了這個解決方案: 如何在 Android 中以編程方式指定視圖的樣式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM