天天看点

android中scrollview嵌套listview的问题

这里记录下关于scrollview嵌套listview的问题,一般来说如果直接在scrollview里面前天一个普通的listview, 用LinearLayout包裹起来,跑起来后发现listview值显示一行,这里就需要做一下处理了,自定义下listview

public class NoScrollListView extends ListView {
    public NoScrollListView(Context context) {
        super(context);
    }

    public NoScrollListView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        
    }

    public NoScrollListView(Context context, AttributeSet attributeSet, int i) {
        super(context, attributeSet, i);
    }

    /**
     * 重写该方法,达到使ListView适应ScrollView的效果
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
    }
           

除了这个,还有一点,就是你在进入界面会发现

scrollview嵌套listview运行后最先显示出来的位置不在顶部而是中间问题

这个地方有两个方法可以解决

第一可以拿到scrollview对象,然后设置

mScrov.smoothScrollTo(0,Integer.MAX_VALUE);
           

让系统达不到这个最大值 ,他就会显示第一条了, 有意思 和 ,清理 缓存 一样, 给系统一个 很大缓存大小, 他清理全部的缓存

还有一种更加简单的办法,直接在父元素 也就是LinearLayout中添加

android:focusableInTouchMode="true"
android:focusable="true"
           

引入这两行代码即可,亲测有用,记录一下.