I have a TableLayout which I add rows programmatically and I'm trying to set "weight" of elements contained in rows programmatically.
I'm trying to do that by setting weightSum
on the TableRow and setting "weight" of the columns using the last parameter of "LayoutParams", but nothing appears; instead if I give a fixed width to elements, code works well.
This is my layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TableLayout
android:id="@+id/sample"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:gravity="center" >
</TableLayout>
</LinearLayout>
This is the code:
public class HomeFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.home, null);
}
@Override
public void onStart() {
super.onStart();
TableLayout tl = (TableLayout)getActivity().findViewById(R.id.sample);
TableRow tr = new TableRow(getActivity());
tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tr.setGravity(Gravity.CENTER);
tr.setWeightSum(1f);
TableRow.LayoutParams lp;
TextView tv1 = new TextView(getActivity());
lp = new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT, 0.6f);
tv1.setText("AAA");
tv1.setLayoutParams(lp);
TextView tv2 = new TextView(getActivity());
lp = new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT, 0.4f);
tv2.setText("BBB");
tv2.setLayoutParams(lp);
tr.addView(tv1);
tr.addView(tv2);
tl.addView(tr);
}
}
Here is the updated code for setting the weightsum and column weight programmatically for a tableLayout.
TableLayout tl = (TableLayout)getActivity().findViewById(R.id.sample);
TableRow tr = new TableRow(getActivity());
tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tr.setGravity(Gravity.CENTER);
tr.setWeightSum(4); //total row weight
TableRow.LayoutParams lp;
lp.weight = 1; //column weight
TextView tv1 = new TextView(getActivity());
lp = new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT, 0.6f);
tv1.setText("AAA");
tv1.setLayoutParams(lp);
TextView tv2 = new TextView(getActivity());
lp = new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT, 0.4f);
tv2.setText("BBB");
tv2.setLayoutParams(lp);
tr.addView(tv1);
tr.addView(tv2);
tl.addView(tr);