通过代码为TextView设置wrap_content的宽度 [英] Setting width to wrap_content for TextView through code

查看:855
本文介绍了通过代码为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆