2015-09-14 31 views
0
工作

我有以下佈局:setLayoutParams不上的切換按鈕

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"> 
     <TableLayout 
      android:id="@+id/master_table" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:stretchColumns="1"> 

     </TableLayout> 
</LinearLayout> 

在代碼中,我添加一些按鈕將由4填充添加每行按鍵表格的佈局:

要添加按鈕:

TableRow row = createTableRow(); 
row.addView(createToggleButton(R.id.button1, getResources().getText(R.string.button1))); 
row.addView(createToggleButton(R.id.button2, getResources().getText(R.string.button2))); 
row.addView(createToggleButton(R.id.button3, getResources().getText(R.string.button3))); 
row.addView(createToggleButton(R.id.button4, getResources().getText(R.string.button4))); 

TableLayout parent = (TableLayout)findViewById(R.id.master_table); 
parent.addView(firstRow); 

createToggleButton的原始版本()方法:

private ToggleButton createToggleButton(int id, CharSequence text) { 
    ToggleButton button = new ToggleButton(this); 
    button.setId(id); 
    button.setTextOff(text); 
    button.setTextOn(text); 
    button.setChecked(false); 
    button.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.button, this.getTheme())); 
    button.setTextColor(getResources().getColorStateList(R.color.button_color)); 

    return button; 
} 

這項工作,我的按鈕被添加到視圖。但是,當我嘗試如下適用的LayoutParams:

private ToggleButton createToggleButton(int id, CharSequence text) { 
    ToggleButton button = new ToggleButton(this); 
    // This line cause the button disappeared !? 
    button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1.0f)); 
    button.setId(id); 
    button.setTextOff(text); 
    button.setTextOn(text); 
    button.setChecked(false); 
    button.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.button, this.getTheme())); 
    button.setTextColor(getResources().getColorStateList(R.color.button_color)); 

    return button; 
} 

我的按鈕不再出現在即使有沒有發生錯誤的觀點。這裏發生了什麼?

+0

如果您回滾到用你的「原始版本」它真的有效?我懷疑 –

回答

0

該錯誤應該由TableRow的寬度引起,並且其ToggleButton子項相互依賴。

集LayoutParam爲的TableRow

row.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT); 

而且改變切換按鈕的佈局,這

button.setLayoutParams(new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT, 1.0f)); 
+0

是的,你是對的。它正在工作。感謝您的幫助。 – RyanB