解决ListView与ScrollView的滑动冲突的方案(非自定义View)
因为在代码中调试的时候,跟源码的行不匹配,乱了,所以没从源码找到什么原因。但是从以下测试代码可以知道,是ScrollView在给ListView传MeasureSpec的时候给SpecSize是有问题的,即ScrollView给的heightSpecSize是ListView一行的高度。我继承了ListView,重写了他的onMeasure方法,目的是改掉ScrollView传入的MeasureSpec,再自定一个MeasureSpec给ListView的onMeasure方法(super.onMeasure(int,int))去测量。结果可以按照给定的MeasureSpec正确测量并显示的,所以结论就是ScrollView给的heightMeasureSpec不对(就是说是给的MeasureSpec不对,然后导致测量ListView时,ListView的测量尺寸小,然后最终回溯导致ScrollView测量尺寸也小)。
而ScrollView是继承自FrameLayout的,但ListView直接作为FrameLayout的child并没有任何问题。但是从ScrollView的onMeasure看,是直接调用FrameLayout的onMeasure方法(除非设置ScrollView的fillViewPort为true),所以并不知道问题出现在ScrollView源码哪里。
下面是我继承ListView重写了onMeasure方法的,在代码中我写死了height为400dp
package com.example.zhangjinbiao.compatablescrollview;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.widget.ListView;
/**
* Created by zhangjinbiao on 11/21/16.
*/
public class StrongListView extends ListView{
public StrongListView(Context context) {
super(context);
}
public StrongListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public StrongListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public StrongListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightSpec = MeasureSpec.makeMeasureSpec(400, MeasureSpec.EXACTLY);
int widthSpec = MeasureSpec.makeMeasureSpec(600, MeasureSpec.EXACTLY);
super.onMeasure(widthSpec, heightSpec);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
可以通过设置ScrollView的fillViewport属性,ListView的尺寸属性就可以有效显示了。fillViewPort类似fillParent,但是具体是什么没有研究。