TableLayout中具有相同宽度的列,*以编程方式*

mar*_*ore 1 android android-layout

我在SO上读到,为了获得一个tablelayout,其中每列具有相同的宽度,您可以设置android:width="0dp"android:weight="1"作为布局参数,它可以工作.我会得到相同的结果,但编程,所以我尝试了这一块代码:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_score, container, false);

    TableRow row = (TableRow)rootView.findViewById(R.id.playerRow);
    for (Player p : game.getPlayers()) {
        TextView t = new TextView(rootView.getContext());
        t.setText(p.getName());
        row.addView(t, new TableLayout.LayoutParams(0, TableLayout.LayoutParams.WRAP_CONTENT, 1f));
        // with the previuos line of code, nothing is showed
        // instead this work: row.addView(t) , but each column doesn't take the maximum width (as I would)

    }

    return rootView;
}
Run Code Online (Sandbox Code Playgroud)

但正如评论中所解释的那样,它不能按预期工作.我无法得到我所缺少的东西.

mar*_*ore 9

我的代码中有错误,LayoutParams是错误的类,我应该使用TableRow.LayoutParams而不是TableLayout.LayoutParams,所以:

row.addView(t, new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT, 1f));
Run Code Online (Sandbox Code Playgroud)

按预期工作.