ScrollView嵌套ListView显示和滑动问题

来源:互联网 发布:dota2淘宝买饰品安全吗 编辑:程序博客网 时间:2024/05/26 20:20

ScrollView嵌套ListView显示和滑动问题

显示问题 

ScrollView中嵌套ListView我测试时,若是高度显示用布局调整android:layout_height=""不管用了,那么这里提供给大家提供两种方法:

方法一:通过在Activity中计算ListView的item高度,并重新布局

int totalHeight = 0;for (int i = 0, len = listAdapter.getCount(); i < len; i++) {    // listAdapter.getCount()返回数据项的数目    View listItem = listAdapter.getView(i, null, listView);    // 计算子项View 的宽高    listItem.measure(0, 0);    // 统计所有子项的总高度    totalHeight += listItem.getMeasuredHeight();}ViewGroup.LayoutParams params = listView.getLayoutParams();params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));// listView.getDividerHeight()获取子项间分隔符占用的高度// params.height最后得到整个ListView完整显示需要的高度listView.setLayoutParams(params);  //内部会自动调用listView.requestLayout();重新布局

方法二:自定义ListView,重写onMeasure()方法

 @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        super.onMeasure(widthMeasureSpec, heightMeasureSpec);        //首次改变显示尺寸是在布局中直接设置的,第二次改变尺寸地方是这里,而第三次改变尺寸可在Activity中        int spec = MeasureSpec.makeMeasureSpec(422, MeasureSpec.AT_MOST);        setMeasuredDimension(widthMeasureSpec,spec); //或采用下边这种方式//        int spec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);//        setMeasuredDimension(widthMeasureSpec,heightMeasureSpec);    }

其实这种情况不一定会出现的,下边的滑动问题才是重点哦!


不能滑动问题

需要注意的是:

1.滑动的前提是listView的高度显示不下所有的数据内容。

2.一次触摸事件(包括按下、滑动、抬起)只有落到listView的覆盖范围,listView才会监听到。

3.上次的触摸事件的处理方式(如请求父控件不拦截),不会影响下一次触摸事件的处理。


三种处理滑动问题的方法:

方法一,设置setOnTouchListener:

listView.setOnTouchListener(new View.OnTouchListener() {    public boolean onTouch(View v, MotionEvent event) {        if(event.getAction() == MotionEvent.ACTION_UP){            listView.requestDisallowInterceptTouchEvent(false); //请求控件不拦截本次触摸事件        }else{
    listView.requestDisallowInterceptTouchEvent(true);
} return false; }});

方法二,自定义ListView,重写onInterceptTouchEvent或dispatchTouchEvent方法:

  @Override    public boolean onInterceptTouchEvent(MotionEvent ev) {        int action = ev.getAction();        switch(action) {            case MotionEvent.ACTION_DOWN :                requestDisallowInterceptTouchEvent(true);            break;            case MotionEvent.ACTION_UP:                requestDisallowInterceptTouchEvent(false);            break;        }        return true;    }

方法三:

@Overridepublic boolean onInterceptTouchEvent(MotionEvent ev) {        requestDisallowInterceptTouchEvent(true);    return super.onInterceptTouchEvent(ev);  //或采用 return true;}

总结:

  还是留给优秀的你来完成吧!O(∩_∩)O哈哈~

0 0
原创粉丝点击