MaxHeightScrollView.java
public class MaxHeightScrollView extends ScrollView {
private int maxHeight;
public MaxHeightScrollView(Context context) {
super(context);
}
public MaxHeightScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
if (!isInEditMode()) {
init(context, attrs);
}
}
public MaxHeightScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
if (!isInEditMode()) {
init(context, attrs);
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public MaxHeightScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
if (!isInEditMode()) {
init(context, attrs);
}
}
private void init(Context context, AttributeSet attrs) {
if (attrs != null) {
TypedArray styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.MaxHeightScrollView);
//200 is a defualt value
int DEFAULT_HEIGHT = 200;
maxHeight = styledAttrs.getDimensionPixelSize(R.styleable.MaxHeightScrollView_max_height, DEFAULT_HEIGHT);
styledAttrs.recycle();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
values/attr.xml
<declare-styleable name="MaxHeightScrollView">
<attr name="max_height" format="dimension"/>
</declare-styleable>
转载自Stack Overflow:
layout - Android: why is there no maxHeight for a View? - Stack Overflow
原作者:SlickDev
MaxHeightScrollView是一个自定义的Android组件,继承自ScrollView并增加了最大高度限制的功能。通过在XML布局文件中使用<declare-styleable>定义了一个max_height属性,允许开发者设置滚动视图的最大高度。在构造函数中检查是否在编辑模式,如果不是,则初始化视图并读取属性值。在onMeasure方法中,根据最大高度重新计算测量规格,确保内容不超过设定的最大高度。
711

被折叠的 条评论
为什么被折叠?



