如何设置tablerows元素的重量?

时间:2013-05-25 17:07:50

标签: android android-tablelayout

我有一个TableLayout,我以编程方式添加行,并且我试图以编程方式设置行中包含的元素的“权重”。

我试图通过在TableRow上设置weightSum并使用“LayoutParams”的最后一个参数设置列的“权重”来做到这一点,但没有出现;相反,如果我给元素一个固定的宽度,代码效果很好。

这是我的布局:

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

这是代码:

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

1 个答案:

答案 0 :(得分:2)

以下是用于以编程方式为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);