ListView在ScrollView中只显示一行浅析

解决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,但是具体是什么没有研究。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值