(原创)可支持最大高度的NestedScrollView
前言
最近写一个dialog,里面有一个ScrollView需要设置最大的高度
但是发现ScrollView是不支持最大高度的
于是自己动手写一个出来
代码
代码很简单,直接贴出来
class MaxHeightNestedScrollView : NestedScrollView {private var maxHeightPercent = 0.5fconstructor(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 = heightMeasureSpectry {val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManagerval display: Display = wm.defaultDisplayval 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滑动