你需要创建一个扩展了
ScrollView
的自定义视图,并在你的 XML 中使用该视图。
public class ScrollViewWithMaxHeight extends ScrollView {
public static int WITHOUT_MAX_HEIGHT_VALUE = -1;
private int maxHeight = WITHOUT_MAX_HEIGHT_VALUE;
public ScrollViewWithMaxHeight(Context context) {
super(context);
init(context, null, 0, 0);
}
public ScrollViewWithMaxHeight(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0, 0);
}
public ScrollViewWithMaxHeight(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle, 0);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes){
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs, R.styleable.custom_ScrollViewWithMaxHeight, defStyleAttr, defStyleRes);
maxHeight =
a.getDimensionPixelSize(R.styleable.max_height,maxHeight);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
try {
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (maxHeight != WITHOUT_MAX_HEIGHT_VALUE
&& heightSize > maxHeight) {
heightSize = maxHeight;
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.AT_MOST);
getLayoutParams().height = heightSize;
} catch (Exception e) {
LogManager.error(this, "onMesure", "Error forcing height", e);
} finally {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void setMaxHeight(int maxHeight) {
this.maxHeight = maxHeight;
}
}
您还需要在值文件夹中创建一个attrs.xml文件,并将其添加到其中。
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">
<declare-styleable name="custom_ScrollViewWithMaxHeight">
<attr name="max_height" format="dimension" />
</declare-styleable>
</resources>
你可以像这样引用视图:
<the.package.where.the.view.is.ScrollViewWithMaxHeight
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:max_height="150dp">
</the.package.where.the.view.is.ScrollViewWithMaxHeight>
app:max_height="yourMaxHeightInDp"
,也可以通过编程方式调用。 - Niza Siwale