问题
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 aRelativeLayout
- Set the
layout_width
to0dp
and use alayout_weight
in aLinearLayout
回答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