2012-07-10 106 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"); 
相關問題