美文网首页
Android使用autolayout库后动态设置TextVie

Android使用autolayout库后动态设置TextVie

作者: 海_3efc | 来源:发表于2021-07-13 14:36 被阅读0次

现象:最近写项目的时候需要动态设置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);

相关文章

网友评论

      本文标题:Android使用autolayout库后动态设置TextVie

      本文链接:https://www.haomeiwen.com/subject/yjqspltx.html