天天看点

自定义ScrollView最大内容显示高度

最近项目中遇到了这样一种显示效果,当ScrollView中显示内容量小的时候自适应高度不滚动,当ScrollView中显示内容量大的时候需要将其高度设置为屏幕高度的一半且可以滚动查看,由于ScrollView没有设置其最大高度的属性,所以就自定义了一个ScrollView来满足我们的显示要求。

自定义一个View继承ScrollView并重写其onMeasure方法,在此方法中设置控件最大高度不能超过屏幕高度的一半(当然大家可以根据自己的需要来进行设置)。

代码如下:

public class MyScrollView extends ScrollView {

    private Context mContext;

    public MyScrollView(Context context) {
        this(context, null);
    }

    public MyScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, );
    }

    public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        try {
            Display display = ((Activity) mContext).getWindowManager().getDefaultDisplay();
            DisplayMetrics d = new DisplayMetrics();
            display.getMetrics(d);
            // 设置控件最大高度不能超过屏幕高度的一半
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(d.heightPixels / , MeasureSpec.AT_MOST);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 重新计算控件的宽高
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
           

在布局文件中使用:

<com.wiggins.widget.MyScrollView
 android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fadingEdge="none"
    android:fillViewport="true"
    android:overScrollMode="never">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/dip20"
        android:layout_marginRight="@dimen/dip20"
        android:textColor="@color/black"
        android:textSize="@dimen/dip15" />
</com.wiggins.widget.MyScrollView>
           

注:

1、去除ScrollView边界阴影

1.1 在xml中添加:android:fadingEdge=”none”

1.2 代码中添加:scrollView.setHorizontalFadingEdgeEnabled(false);

2、去除ScrollView拉到顶部或底部时继续拉动后出现的阴影效果,适用于2.3及以上

2.1 在xml中添加:android:overScrollMode=”never”

3、当ScrollView子布局不足以铺满全屏的时候其高度就是子布局高度之和,此时如果想让ScrollView铺满全屏时只需要设置以下属性即可

3.1 在xml中添加:android:fillViewport=”true”

通过以上配置后就可以实现我们所要达到的效果了。

继续阅读