Question

I have an application that generates buttons inside a table view as shown below:

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 );

           }
}

Is there a way to programmatically set the button width to wrap_content and height to match_parent?

If this is not possible, is there a way to programmatically evenly space out the buttons in the row?

Thanks.

Was it helpful?

Solution

Try This:

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

Try use Weight in button. Give table row weightsum=10. and divide it to buttons as per your req. like btn1.weight=3; btn2.weight=5;btn3.weight=2; this is like using % in HTML. if you set weightsum = 10 that means it will use 100% of its parent view. and using weight=3 for button means it will use 3/10 of total row size. it is just for width so you need to set width =0 for every view where you are assigning weight.

for weight use like this:

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

where 3f is weight. but first setweight sum to 10 in tablerow.

Hope it Helps!!!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top