我有一个TableLayout .

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tab">

</TableLayout>

这就是我动态尝试向其添加行的方式 .

TableLayout tl = findViewById(R.id.tab);
tl.removeAllViews();
tl.setColumnStretchable(2,true);
//tl.setColumnStretchable(1,false);
TableLayout.LayoutParams lp = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,
            TableLayout.LayoutParams.WRAP_CONTENT);
lp.weight = 1;
TableRow.LayoutParams hparams1 = new TableRow.LayoutParams(0,TableRow.LayoutParams.MATCH_PARENT);
TableRow.LayoutParams hparams2 = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,TableRow.LayoutParams.MATCH_PARENT);
hparams1.setMargins(1,1,1,1);
hparams2.setMargins(1,1,1,1);
TableRow row = new TableRow(this);
row.setBackgroundColor(Color.BLACK);
row.setLayoutParams(lp);
TextView h1 = new TextView(this);
TextView h2 = new TextView(this);
TextView h3 = new TextView(this);
TextView h4 = new TextView(this);
h1.setText("col1");
h2.setText("col2");
h3.setText("col3");
h4.setText("col4");
h1.setTextSize(23);
h2.setTextSize(23);
h3.setTextSize(23);
h4.setTextSize(23);
h1.setBackgroundColor(Color.GREEN);
h2.setBackgroundColor(Color.GREEN);
h3.setBackgroundColor(Color.GREEN);
h4.setBackgroundColor(Color.GREEN);
h1.setLayoutParams(hparams2);
h2.setLayoutParams(hparams2);
h3.setLayoutParams(hparams1);
h4.setLayoutParams(hparams2);
row.addView(h1);
row.addView(h2);
row.addView(h3);
row.addView(h4);
tl.addView(row,0);

这给了我一个漂亮的tablerow,其宽度等于屏幕宽度,col1,col2,col4的宽度等于它们的内容,col3拉伸以填充行的其余部分 . 喜欢这个https://i.imgur.com/qGfYyxb.jpg

但是,如果我取消注释第4行或尝试在代码中的任何位置取消拉伸列,则4列不再占据整个行宽,即 . 整个屏幕宽度 . 喜欢这个https://i.imgur.com/js4jNAf.jpg

为什么会这样? isnt col2默认是一个未拉伸的列?

最后,如何在没有这个奇怪的宽度问题的情况下拉伸拉伸的柱并拉伸另一个柱?谢谢 .