Setting width to wrap_content for TextView through code

Android_programmer_camera picture Android_programmer_camera · Jan 31, 2011 · Viewed 109.8k times · Source

Can anyone help me how to set the width of TextView to wrap_content through code and not from XML?

I am dynamically creating a TextView in code ,so is there anyway to how to set its width to wrap_content through code?

Answer

Franco picture Franco · Jan 31, 2011
TextView pf = new TextView(context);
pf.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

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)); 

or

parentView.addView(pf, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));