簡體   English   中英

Android-在表格行中以編程方式設置按鈕寬度

[英]Android - set button width programmatically inside a tablerow

我有一個在表格視圖內生成按鈕的應用程序,如下所示:

TableLayout table = (TableLayout) findViewById( R.id.tableLayout1 );

    for(int i = 0 ; i < Gatorade.getVariant().length ; i++){
           int buttonsInRow = 0;
           int numRows = table.getChildCount();

           TableRow row = null;

           if( numRows > 0 ){
                row = (TableRow) table.getChildAt( numRows - 1 );
                buttonsInRow = row.getChildCount();         
           }

           if( numRows == 0 || buttonsInRow == 3 ){
                row = new TableRow( this );
                table.addView( row );
                buttonsInRow = 0;
           }
           if( buttonsInRow < 3 ){
                Button b = new Button( this );
                b.setText(Gatorade.getVariant()[i]);
                //b.setWidth(pixels)
                //b.setWidth()

                row.addView( b, 100, 50 );

           }
}

有沒有辦法以編程方式將按鈕的寬度設置為wrap_content並將高度設置為match_parent

如果無法做到這一點,是否有辦法以編程方式均勻地隔開行中的按鈕?

謝謝。

嘗試這個:

LayoutParams lp = new TableRow.LayoutParams(android.widget.TableRow.LayoutParams.WRAP_CONTENT,android.widget.TableRow.LayoutParams.MATCH_PARENT);
btn.setLayoutParams(lp);

嘗試使用“重量”按鈕。 給表行weightsum = 10。 並根據您的要求將其划分為按鈕。 像btn1.weight = 3; btn2.weight = 5; btn3.weight = 2; 這就像在HTML中使用%。 如果將weightsum設置為10,則表示它將使用其父視圖的100%。 並為按鈕使用weight = 3意味着它將使用總行大小的3/10。 它僅用於寬度,因此您需要為分配權重的每個視圖將寬度設置為= 0。

對於這樣的重量用途:

LayoutParams lp = new TableRow.LayoutParams(0,android.widget.TableRow.LayoutParams.MATCH_PARENT,3f);

其中3f是重量。 但第一個setweight總和為10。

希望能幫助到你!!!

暫無
暫無

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

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