(原创)可支持最大高度的NestedScrollView

前言

最近写一个dialog,里面有一个ScrollView需要设置最大的高度
但是发现ScrollView是不支持最大高度的
于是自己动手写一个出来

代码

代码很简单,直接贴出来

class MaxHeightNestedScrollView : NestedScrollView {
  private var maxHeightPercent = 0.5f
  constructor(context: Context) : this(context, null)
  constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)
  constructor(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int) : super(context, attributeSet, defStyleAttr) {
    val array = context.obtainStyledAttributes(attributeSet, R.styleable.max_height_scrollview)
    maxHeightPercent = array.getFloat(R.styleable.max_height_scrollview_maxHeightPercent, 0.5f)
  }

  override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    var heightMS = heightMeasureSpec
    try {
      val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
      val display: Display = wm.defaultDisplay
      val d = DisplayMetrics()
      display.getMetrics(d)
      val height = (d.heightPixels * maxHeightPercent).toInt()
      heightMS = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST)
    } catch (e: Exception) {
      e.printStackTrace()
    }
    super.onMeasure(widthMeasureSpec, heightMS)
  }

}

在xml使用的地方这样设置最大高度即可:

app:maxHeightPercent="0.6"

其中0.6代表最大高度为屏幕的0.6
其实分析下代码之后,我们也可以很容易的来设置固定的值
这里就不写出来了

注意点

需要注意的第一点是:
这里记得要继承NestedScrollView
一开始我是继承的ScrollView
最后发现如果里面放入的是RecycleView
会出现RecycleView最后一行显示不出来的问题
如果是继承了NestedScrollView就没这个问题了
同样的,以后想要滚动条里面加入RecycleView
最好也是用NestedScrollView

第二点
scrollview嵌套多个RecycleView时,如果要禁止RecycleView的滑动
可以调用RecycleView的setNestedScrollingEnabled(boolean enabled) 方法
传入false即可禁止内部的RecycleView滑动

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值