I have put a TextView inside a ScrollView in Android:
<ScrollView android:layout_width = "fill_parent" android:layout_height = "wrap_content"> <TextView android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </ScrollView> With this configuration, the scrollview grows to wrap the textview-content. How can I achieve that the scrollview takes only as much space as needed (for few text), but at the same time limit the size to 100dp (for long texts) ?
- If I set layout_height to 100dp, a lot of space is wasted when the text is short
- If I set layout_height to wrap_content, the scrollview runs the risk to fill the whole screen, but I don't want the whole sreen to only contain this scrollview. It should be 100dp heigh as a maximum.
The solution which was found:
Thank you for alls answers. For all people that have the same issue, here goes the accepted solution: Create a custom ScrollView class an use this class inside your xml file instead ScrollView. Then override onMeasure() method:
public class ScrollMyVew extends ScrollView { public static final int maxHeight = 100; // 100dp // default constructors @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { heightMeasureSpec = MeasureSpec.makeMeasureSpec(dpToPx(getResources(),maxHeight), MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } private int dpToPx(Resources res, int dp) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, res.getDisplayMetrics()); } } This solution is taken from https://stackoverflow.com/a/23617530/3080611