解決ScrollView巢狀ViewPager出現的滑動衝突問題

Main-zy發表於2014-07-17

很簡單,只需要重寫ScrollView就可以了



import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ScrollView;
 
/**重寫ScrollView
 * 解決ScrollView巢狀ViewPager出現的滑動衝突問題
 * @date 2014-7-17 上午11:04:22
 * @author ZhangYi
 *
 */
public class MyScrollView extends ScrollView {
    private boolean canScroll;
 
    private GestureDetector mGestureDetector;
    View.OnTouchListener mGestureListener;
 
    public MyScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mGestureDetector = new GestureDetector(new YScrollDetector());
        canScroll = true;
    }
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if(ev.getAction() == MotionEvent.ACTION_UP)
            canScroll = true;
        return super.onInterceptTouchEvent(ev) && mGestureDetector.onTouchEvent(ev);
    }
 
    class YScrollDetector extends SimpleOnGestureListener {
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            if(canScroll)
                if (Math.abs(distanceY) >= Math.abs(distanceX))
                    canScroll = true;
                else
                    canScroll = false;
            return canScroll;
        }
    }
}


Xml呼叫自定義ScrollView方法


把原來的ScrollView元件名字換成   包名.MyScrollView 就可以了


<com.zy.myview.ScrollView  
        android:layout_width="fill_parent"
		android:layout_height="wrap_content" 
		android:scrollbars="none"
        >  
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:orientation="vertical" >
........


遇到同問題得試試吧

相關文章