Programatically assign column weight in a row, within TableLayout
I want to define just one row in my table. To this row, I want to add 3 columns, with the following widths:
textView1 : should be as wide as its contents
viewDivider: should be 2px wide
TextView2: should occupy the remaining area of the tablerow.
However, I am not able to achieve the above layout, programatically. Here is the code:
public class Copy_2_of_Test extends Activity {
TableLayout tableLayout = null;
TextView textView1 = null;
TextView textView2 = null;
View viewDivider = null;
TableLayout tab = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView (R.layout.test);
tableLayout = (TableLayout)this.findViewById(R.id.mainTable);
addViews();
}
private void addViews() {
// table row with layout params of type TableLayout.LayoutParams
TableRow tr = new TableRow(this);
tr.setLayoutParams(new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
// Textview 1 with layout params of type TableRow.LayoutParams
textView1 = new TextView(this);
textView1.setText("Value1");
textView1.setTextColor(Color.BLACK);
textView1.setBackgroundColor(Color.YELLOW);
textView1.setLayoutParams(new TableRow.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.FILL_PARENT));
tr.addView(textView1);
viewDivider = new View (this);
viewDivider.setLayoutParams(new TableRow.LayoutParams(
2,
LayoutParams.FILL_PARENT));
viewDivider.setBackgroundColor(Color.MAGENTA);
tr.addView(viewDivider);
// Textview 2 with layout params of type TableRow.LayoutParams
textView2 = new TextView(this);
textView2.setText("Value2 Value2 Value2 Value2 ");
textView2.setTextColor(Color.BLACK);
textView2.setBackgroundColor(Color.YELLOW);
textView2.setLayoutParams(new TableRow.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.FILL_PARENT));
tr.addView(textView2);
// Add row to TableLayout.
tableLayout.addView(tr,new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
}
}
And here's test.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="*"
android:background="@color/black"
android:id="@+id/mainTable">
</TableLayout>
I am facing thefollowing issues with the above layout:
1) textView1 occupies more width that its contents.
2) viewDivider occupies a lot of width and is not restriced to 2px
Thanks for the he开发者_JS百科lp.
Try Using setWidth() method for setting width.
For Reference
精彩评论