scrollview和viewpager嵌套冲突的问题

scrollview下包括了一个viewpager,会产生这样的问题:viewpager的内容不能显示。解决方法如下:

第一种:从scrollview解决

重写scrollview,在其中重写onInterceptTouchEvent方法,代码如下:

@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
	    switch (ev.getAction()) {
	        case MotionEvent.ACTION_DOWN:
	            xDistance = yDistance = 0f;
	            lastX = ev.getX();
	            lastY = ev.getY();
	            break;
	        case MotionEvent.ACTION_MOVE:
	            final float curX = ev.getX();
	            final float curY = ev.getY();
	            xDistance += Math.abs(curX - lastX);
	            yDistance += Math.abs(curY - lastY);
	            lastX = curX;
	            lastY = curY;
	            if(xDistance > yDistance)
	                return false;
	    }
	    return super.onInterceptTouchEvent(ev);
	}
第二种:从viewpager解决

重写viewpager,自适应高度,代码如下:

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
 
        int height = 0;
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            int h = child.getMeasuredHeight();
            if (h > height)
                height = h;
        }
 
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
 
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
这样可以解决viewpager内容不显示的问题,但是左右滑动会不流畅,解决如下:

@Override  
    public boolean dispatchTouchEvent(MotionEvent ev) { 
	switch(ev.getAction()){
	case MotionEvent.ACTION_DOWN:
		xDown = ev.getX();  
	        yDown = ev.getY();
	break;
	case MotionEvent.ACTION_MOVE:
		xMove = ev.getX();  
	        yMove = ev.getY();
		offsetX += ev.getX() - xDown;
		offsetY += ev.getY() - yDown;
		xDown = ev.getX();
		yDown = ev.getY();
	            
		if ( Math.abs(offsetX) > Math.abs(offsetY) || Math.abs(offsetX) == 0) {  
			getParent().requestDisallowInterceptTouchEvent(true);  
	        } else {
	            	getParent().requestDisallowInterceptTouchEvent(false);
	        }
	break;
	case MotionEvent.ACTION_UP:
		offsetX = 0;
		offsetY = 0;
		getParent().requestDisallowInterceptTouchEvent(false);
	break;
	}
        return super.dispatchTouchEvent(ev);  
    } 

参考:

http://www.csdn123.com/html/itweb/20130928/142334.htm

http://zhidao.baidu.com/link?url=sys_7XXvHkuq50X4HPIdYlal3oDjfq6Mbn0RFMjuX1zZOpmOTTAQuxo9G7uxzSx2aMvibU4x8HG4Uyio5Y-tdNDFNr1o7yxQAeEJy-FYUy_

你可能感兴趣的:(scrollview和viewpager嵌套冲突的问题)