ScroolView 控制最大高度

这篇博客介绍了一个需求,即在Android中创建一个弹窗,内含一个TextView显示可能很长的提示文字。为了保持弹窗美观,限制了TextView的最大高度。当文字未超过最大高度时,TextView自适应高度不滚动;超过则启用ScrollView滚动功能。通过自定义MaxHeightScrollView类实现了这一功能,代码中详细展示了如何限制TextView的高度并处理滚动行为。
摘要由CSDN通过智能技术生成

写项目是碰到的需求,是一个弹窗里面是提示文字,文字有可能会很多,作为一个弹窗高度不能太高,太高就不美观了,所以要限定弹窗的高度,需要满足以下几点:

* ScrollView 嵌套 TextView,限制TextView最大高度。
* TextView未达到最大高度时,自适应高度且不能滚动
* TextView达到最大高度时,可滚动。

那就对 ScrollView 进行调整:

public class MaxHeightScrollView extends ScrollView {

    private int maxHeight;

    public MaxHeightScrollView(Context context) {
        super(context);
    }

    public MaxHeightScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize(context, attrs);
    }

    public MaxHeightScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize(context, attrs);
    }


    private void initialize(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MaxHeightScrollView);
        maxHeight = typedArray.getLayoutDimension(R.styleable.MaxHeightScrollView_maxHeight, maxHeight);
        typedArray.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (maxHeight > 0) {
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

}

XML :

       <com.test.widget.MaxHeightScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/dp_10"
            android:fillViewport="true"
            android:scrollbars="vertical"
            app:maxHeight="@dimen/dp_300">

            <TextView
                android:id="@+id/tv_msg"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text=""
                android:textColor="@color/col_333333"
                android:textSize="@dimen/sp_14" />

        </com.test.widget.MaxHeightScrollView>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值