Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically adjust the TextView height according to the size of the String?

I want to know how to automatically adjust the size of the TextView according to the length of the String. I am getting some data from another Intent as a String and storing it in a TextView. If I leave it small, the whole text won't fit and only half of it is displayed. If I leave a big space for the TextView it does not look nice on the screen.

The solution I found online was using extends TextView and using this method gives errors in my class and I have to change a lot of functions because of this

like image 876
RustyTheron Avatar asked May 22 '15 21:05

RustyTheron


2 Answers

Use a multi-line TextView and set layout_height to wrap_content:

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:singleLine="false"/>

Note: If you set layout_width to wrap_content it won't work properly. If you don't want the TextView to take up the entire width of the parent view then either:

  • Set it to a fixed width in XML, or
  • Set the width programmatically, or
  • Set layout_alignLeft/layout_alignRight etc in a RelativeLayout
  • Set the layout_width to 0dp and use a layout_weight in a LinearLayout
like image 87
samgak Avatar answered Oct 22 '22 11:10

samgak


If you are using xml file, just do this,

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="false"/>

And if you want to do dynamically do like this,

TextView textView= new TextView(activity);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
textView.setLayoutParams(param);
like image 30
Exigente05 Avatar answered Oct 22 '22 10:10

Exigente05