2013-05-14 35 views
0

我有一系列按鈕要添加到TableLayout中的不同行中。每個按鈕都需要有不同的寬度。但是,每個按鈕的寬度最終都設置爲等於最大寬度的按鈕。有人可以讓我知道如何解決這個問題嗎?TableLayout中不正確的Android按鈕寬度

 <TableLayout 
      android:id="@+id/table_to_fill" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" > 

      <TableRow 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" > 

       <TextView 
        android:id="@+id/cat" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="" 
        android:textSize="12sp" 
        android:textStyle="bold" 
        android:typeface="serif" > 
       </TextView> 

       <TextView 
        android:id="@+id/num_high" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="" 
        android:textSize="12sp" 
        android:textStyle="bold" 
        android:typeface="serif" > 
       </TextView> 
      </TableRow> 
     </TableLayout> 

Java代碼:

for (int i =0; i< 5; ++i){ 
     TableRow row = new TableRow(this); 
     TextView t1 = new TextView(this); 
     t1.setText("cat: "); 
     t1.setTextSize(12); 
     row.addView(t1); 
     Button b1 = new Button(this); 

     b1.setText(numHighRisk.toString()); 
     b1.setTextSize(12); 
     b1.setPadding(0, 0, 0, 0); 
     row.addView(b1); 
     int width; 
     if (i > 2) 
      width = 20; 
     else 
      width = 40; 
     int heightDp = (int) (25 * scale + 0.5f); 
     int widthDp = (int) (width * scale + 0.5f); 


     ViewGroup.LayoutParams params = b1.getLayoutParams(); 
     params.height = heightDp; 
     params.width = widthDp; 
     b1.setLayoutParams(params); 

      TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT); 
     table.addView(row,rowParams); 
    } 

(每個按鈕都有使用此代碼相同的寬度)

回答

1

呀表佈局中的所有項目將在以使他們正確對齊具有相同的大小,你可以做一件事情,嘗試給你的按鈕留有餘量,這樣它們的尺寸就會減小,不同按鈕的邊距也會不同。 例如,

android:layout_marginLeft="40dp" 
android:layout_marginRight="40dp" 
+1

你試過了嗎? – Shubham 2013-05-14 06:00:43

0

對於某些實驗,我能夠通過首先將每個按鈕到的FrameLayout,然後加入的FrameLayout到行以實現不同的寬度。