Setting width in wrap_content for TextView with code

Can someone help me set the width of the TextView to wrap_content via code, and not from XML?

I am dynamically creating TextView code in the code, anyway, how to set its width in wrap_content through the code?

+66
android textview
Jan 31 '11 at 18:18
source share
5 answers
 TextView pf = new TextView(context); pf.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 

or

 parentView.addView(pf, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
+98
Jan 31 '11 at 18:20
source share

There is another way to achieve the same result. If 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); 
+64
Jan 28 '14 at 19:00
source share

Solution for changing the width of the TextView 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 
+36
Apr 25 '16 at 15:13
source share

I think this code answers your question

 RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.desc1.getLayoutParams(); params.height = RelativeLayout.LayoutParams.WRAP_CONTENT; holder.desc1.setLayoutParams(params); 
+1
Jul 11 '18 at 21:18
source share

I host an Android 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 */ 
0
Jan 28 '19 at 10:48
source share



All Articles