通过代码将 TextView 的宽度设置为 wrap_content [英] Setting width to wrap_content for TextView through code
本文介绍了通过代码将 TextView 的宽度设置为 wrap_content的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能帮助我如何通过代码而不是 XML 将 TextView
的宽度设置为 wrap_content
?
Can anyone help me how to set the width of TextView
to wrap_content
through code and not from XML?
我在代码中动态创建一个TextView
,那么有没有办法通过代码将其宽度设置为wrap_content
?
I am dynamically creating a TextView
in code ,so is there anyway to how to set its width to wrap_content
through code?
推荐答案
TextView pf = new TextView(context);
pf.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
对于ConstraintLayout
等不同的布局,它们都有自己的LayoutParams
,像这样:
For different layouts like ConstraintLayout
and others, they have their own LayoutParams
, like so:
pf.setLayoutParams(new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
或
parentView.addView(pf, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
这篇关于通过代码将 TextView 的宽度设置为 wrap_content的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文