Set the layout weight of a TextView programmatically
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);