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

给你一囗甜甜゛ 提交于 2019-12-12 09:41:14

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/30406021/how-to-automatically-adjust-the-textview-height-according-to-the-size-of-the-str

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!