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

一世执手 提交于 2019-12-05 12:32:15

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

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