TextView在设置LayoutParam宽度后得到错误的宽度值



我试图设置TextView宽度,我使用LayoutParam来设置视图宽度,但在我setLayoutParam上TextView然后打印它的宽度后,它返回不同的值到我设置的值。

这里是日志和代码:

日志
public ViewHolder(@NonNull View itemView) {
super(itemView);
colYear = itemView.findViewById(R.id.colYear);
colAge = itemView.findViewById(R.id.colAge);
colMoney = itemView.findViewById(R.id.colMoney);
ViewGroup.LayoutParams yearParam = colYear.getLayoutParams();
yearParam.width = firstColWidth;
colYear.setLayoutParams(yearParam);
ViewGroup.LayoutParams ageParam = colAge.getLayoutParams();
ageParam.width = secondColWidth;
colAge.setLayoutParams(ageParam);
Log.d("Adapter","firstColWidth:"+firstColWidth);
Log.d("Adapter","secondColWidth:"+secondColWidth);
colYear.post(()->Log.d("Adapter","colYear:"+colYear.getWidth()));
colAge.post(()->Log.d("Adapter","colAge:"+colAge.getWidth()));
}

我也尝试直接使用TextView.setWidth(),但仍然有同样的问题。

找到了问题,我使用一个LinearLayout包含TextView和每个TextView有默认的layout_weight,删除layout_weight然后工作良好。

最新更新