[android] Setting width to wrap_content for TextView through code

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?

This question is related to android textview

The answer is


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

A little update on this post: if you are using ktx within your Android project, there is a little helper method that makes updating LayoutParams a lot easier.

If you want to update e.g. only the width you can do that with the following line in Kotlin.

tv.updateLayoutParams { width = WRAP_CONTENT }

Solution for change TextView width to wrap content.

textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT; 
textView.requestLayout();  
// Call requestLayout() for redraw your TextView when your TextView is already drawn (laid out) (eg: you update TextView width when click a Button). 
// If your TextView is drawing you may not need requestLayout() (eg: you change TextView width inside onCreate()). However if you call it, it still working well => for easy: always use requestLayout()

// Another useful example
// textView.getLayoutParams().width = 200; // For change `TextView` width to 200 pixel

I am posting android Java base multi line edittext.

EditText editText = findViewById(R.id.editText);/* edittext access */

ViewGroup.LayoutParams params  =  editText.getLayoutParams(); 
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
editText.setLayoutParams(params); /* Gives as much height for multi line*/

editText.setSingleLine(false); /* Makes it Multi line */

I think this code answer your question

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) 
holder.desc1.getLayoutParams();
params.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
holder.desc1.setLayoutParams(params);

There is another way to achieve same result. In case you need to set only one parameter, for example 'height':

TextView textView = (TextView)findViewById(R.id.text_view);
ViewGroup.LayoutParams params = textView.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(params);