2011-11-14 13 views
5

我想了一堆按鈕添加到像這樣的佈局:如何設置一個按鈕的參數編程

for(int i = 0; i < 10; i++) { 
    Button button = new Button(this); 
    button.setText("" + i); 
    ((LinearLayout)dialog.findViewById(R.id.Buttons)).addView(button); 
} 

我的問題是我怎麼做到這一點編程到所有的按鈕:

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center_horizontal" 
    android:textSize="32dip" /> 

我一直在看LayoutParams,但它看起來不完整。像我如何設置textSize爲32傾角?

回答

13

使用下面的代碼設置你的屬性

button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 32); 
+0

雖然我在引力方面遇到了問題。 setGravity(Gravity.CENTER_HORIZONTAL)在xml文件中的作用與android:layout_gravity =「center_horizo​​ntal」不同。 xml文件按鈕居中,但不是使用setGravity()創建的按鈕。 – Espen

+0

嘗試使用佈局參數:LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,Gravity.CENTER_HORIZONTAL); – dymmeh

+0

或初始化params調用後:params.gravity = Gravity.CENTER_HORIZONTAL; – dymmeh

3

使用的LayoutParams的高度,寬度和重力與

LinearLayout.LayoutParams (int width, int height) 

在那裏你可以使用WRAP_CONTENT爲整數。

然後最後兩個有Button.setGravity()Button.setTextSize()

希望這會有所幫助。

+0

我怎樣才能通過使用Button.setTextSize()指定dip? – Espen

+0

public void setTextSize(int unit,float size); 其中unit是「COMPLEX_UNIT_DIP」,size =文本大小。 –

0

您將使用LayoutParams對象作爲佈局設置,並使用Button類中的文字大小設置setTextSize()

您也可以使用setGravity()來設置重力。

0

TextSize不在佈局參數內。要設置TEXTSIZE你必須

button.setTextSize(32); 
4

LayoutParams涉及父ViewGroup其中將包含的觀點。所以在你的情況下,這是一個LinearLayout,所以你需要爲那個創建參數。這裏就是我說的:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
      LayoutParams.WRAP_CONTENT); 
button.setLayoutParams(params); 
button.setGravity(Gravity.CENTER_HORIZONTAL); 
button.setTextSize(32); 

如果要指定大小單位使用的文字:

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
lp.weight = 1f; 

Button button = new Button(this); 
button.setLayoutParams(lp); 
button.setText("" + i); 
((LinearLayout)dialog.findViewById(R.id.Buttons)).addView(button); 
相關問題