Set the layout weight of a TextView programmatically
I'm trying to dynamically create TableRow
objects and add them to a TableLayout
.
The TableRow
objects has 2 items, a TextView
and a CheckBox
. The TextView
items need to have their layout weight set to 1 to push the CheckBox
items to the far right.
I can't find documentation on how to programmatically set the layout weight of a TextView
item.
You have to use TableLayout.LayoutParams
with something like this:
TextView tv = new TextView(v.getContext());
tv.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
The last parameter is the weight.
The answer is that you have to use TableRow.LayoutParams, not LinearLayout.LayoutParams or any other LayoutParams.
TextView tv = new TextView(v.getContext());
LayoutParams params = new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f);
tv.setLayoutParams(params);
The different LayoutParams are not interchangeable and if you use the wrong one then nothing seems to happen. The text view's parent is a table row, hence:
http://developer.android.com/reference/android/widget/TableRow.LayoutParams.html
In the earlier answers weight is passed to the constructor of a new SomeLayoutType.LayoutParams object. Still in many cases it's more convenient to use existing objects - it helps to avoid dealing with parameters we are not interested in.
An example:
// Get our View (TextView or anything) object:
View v = findViewById(R.id.our_view);
// Get params:
LinearLayout.LayoutParams loparams = (LinearLayout.LayoutParams) v.getLayoutParams();
// Set only target params:
loparams.height = 0;
loparams.weight = 1;
v.setLayoutParams(loparams);
TextView txtview = new TextView(v.getContext());
LayoutParams params = new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f);
txtview.setLayoutParams(params);
1f is denotes as weight=1; you can give 2f or 3f, views will move accoding to the space
just set layout params in that layout like
create param variable
android.widget.LinearLayout.LayoutParams params = new android.widget.LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1f);
1f is weight variable
set your widget or layout like
TextView text = (TextView) findViewById(R.id.text);
text.setLayoutParams(params);