TextView等组件的LayoutParams不能随便用,不然组件不显示

TableLayout.LayoutParams lpRow = new TableLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lpRow.setMargins(1, 0, 1, 1);

LinearLayout.LayoutParams lpText = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
lpText.setMargins(1, 0, 0, 0);

TableRow tableRow = new TableRow(layVeri.getContext());
tableRow.setLayoutParams(lpRow);

TextView tvCode = new TextView(tableRow.getContext());
tvCode.setText("付月刚1号田地");
tvCode.setTextSize(20);
tvCode.setGravity(Gravity.CENTER_VERTICAL);
tvCode.setPadding(5, 8, 5, 8);
tvCode.setSingleLine(true);
tvCode.setEllipsize(TruncateAt.END);
tvCode.setBackgroundColor(getResources().getColor(R.color.backColor));
tvCode.setLayoutParams(lpText);

上面的代码,tvCode没有显示出来,原因是tvCode.setLayoutParams(lpText)这句,

lpText设置了LinearLayout.LayoutParams 参数,应该是只设置其直接父容器(TableRow)的LayoutParams,

设置成:TableRow.LayoutParams lpText = new TableRow.LayoutParams(  就可以了。

由些可以结论,设置组个把的LayoutParams,必须是父容器的LayoutParams.

原文地址:https://www.cnblogs.com/zmc/p/4311476.html