现象:最近写项目的时候需要动态设置TextView字体的大小,发现通过setTextSize设置后,未生效。
原因:后来断点调试发现设置字体大小后autolayout会重新计算TextView字体大小,这个时候计算出的值变成了xml中默认配置的textSize的大小,把动态设置的textSize值给覆盖了。
解决方案:在动态设置textSize前,需要重新设置TextView的LayoutParam,代码如下:
ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) view.getLayoutParams();
//注意:下面代码直接设置也是无效的
//view.setLayoutParams(layoutParams);
view.setLayoutParams(new ConstraintLayout.LayoutParams(layoutParams));
//setTextSize之前一定要重新设置setLayoutParams!!! 否则设置无效
int textSize = AutoUtils.getPercentHeightSize(72);
//setTextSize 单位PX
view.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
网友评论