226

画面全体をスクロールできるように、レイアウト全体を囲む ScrollView があります。この ScrollView の最初の要素は、水平方向にスクロールできる機能を持つ Horizo​​ntalScrollView ブロックです。水平スクロール ビューに ontouchlistener を追加して、タッチ イベントを処理し、ACTION_UP イベントで最も近い画像にビューを強制的に "スナップ" させました。

だから私が目指している効果は、1 つの画面から別の画面にスクロールでき、指を離すと 1 つの画面にスナップするストック Android のホーム画面のようなものです。

1 つの問題を除いて、これはすべてうまく機能します。ACTION_UP を登録するには、左から右にほぼ完全に水平にスワイプする必要があります。少なくとも縦方向にスワイプすると (多くの人が携帯電話で左右にスワイプする傾向があると思います)、ACTION_UP ではなく ACTION_CANCEL を受け取ります。私の理論では、これは、Horizo​​ntalscrollView がスクロールビュー内にあり、スクロールビューが垂直方向のタッチをハイジャックして垂直方向のスクロールを可能にしているためです。

スクロールビューのタッチイベントを水平スクロールビュー内から無効にするにはどうすればよいですか?

これが私のコードのサンプルです:

   public class HomeFeatureLayout extends HorizontalScrollView {
    private ArrayList<ListItem> items = null;
    private GestureDetector gestureDetector;
    View.OnTouchListener gestureListener;
    private static final int SWIPE_MIN_DISTANCE = 5;
    private static final int SWIPE_THRESHOLD_VELOCITY = 300;
    private int activeFeature = 0;

    public HomeFeatureLayout(Context context, ArrayList<ListItem> items){
        super(context);
        setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        setFadingEdgeLength(0);
        this.setHorizontalScrollBarEnabled(false);
        this.setVerticalScrollBarEnabled(false);
        LinearLayout internalWrapper = new LinearLayout(context);
        internalWrapper.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        internalWrapper.setOrientation(LinearLayout.HORIZONTAL);
        addView(internalWrapper);
        this.items = items;
        for(int i = 0; i< items.size();i++){
            LinearLayout featureLayout = (LinearLayout) View.inflate(this.getContext(),R.layout.homefeature,null);
            TextView header = (TextView) featureLayout.findViewById(R.id.featureheader);
            ImageView image = (ImageView) featureLayout.findViewById(R.id.featureimage);
            TextView title = (TextView) featureLayout.findViewById(R.id.featuretitle);
            title.setTag(items.get(i).GetLinkURL());
            TextView date = (TextView) featureLayout.findViewById(R.id.featuredate);
            header.setText("FEATURED");
            Image cachedImage = new Image(this.getContext(), items.get(i).GetImageURL());
            image.setImageDrawable(cachedImage.getImage());
            title.setText(items.get(i).GetTitle());
            date.setText(items.get(i).GetDate());
            internalWrapper.addView(featureLayout);
        }
        gestureDetector = new GestureDetector(new MyGestureDetector());
        setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                else if(event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL ){
                    int scrollX = getScrollX();
                    int featureWidth = getMeasuredWidth();
                    activeFeature = ((scrollX + (featureWidth/2))/featureWidth);
                    int scrollTo = activeFeature*featureWidth;
                    smoothScrollTo(scrollTo, 0);
                    return true;
                }
                else{
                    return false;
                }
            }
        });
    }

    class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                //right to left 
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    activeFeature = (activeFeature < (items.size() - 1))? activeFeature + 1:items.size() -1;
                    smoothScrollTo(activeFeature*getMeasuredWidth(), 0);
                    return true;
                }  
                //left to right
                else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    activeFeature = (activeFeature > 0)? activeFeature - 1:0;
                    smoothScrollTo(activeFeature*getMeasuredWidth(), 0);
                    return true;
                }
            } catch (Exception e) {
                // nothing
            }
            return false;
        }
    }
}
4

9 に答える 9

283

更新:私はこれを理解しました。私の ScrollView では、onInterceptTouchEvent メソッドをオーバーライドして、Y モーションが > X モーションの場合にのみタッチ イベントをインターセプトする必要がありました。ScrollView のデフォルトの動作は、Y モーションがあるたびにタッチ イベントをインターセプトすることのようです。したがって、この修正により、ScrollView は、ユーザーが意図的に Y 方向にスクロールしている場合にのみイベントをインターセプトし、その場合は ACTION_CANCEL を子に渡します。

以下は、Horizo​​ntalScrollView を含む Scroll View クラスのコードです。

public class CustomScrollView extends ScrollView {
    private GestureDetector mGestureDetector;

    public CustomScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mGestureDetector = new GestureDetector(context, new YScrollDetector());
        setFadingEdgeLength(0);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return super.onInterceptTouchEvent(ev) && mGestureDetector.onTouchEvent(ev);
    }

    // Return false if we're scrolling in the x direction  
    class YScrollDetector extends SimpleOnGestureListener {
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {             
            return Math.abs(distanceY) > Math.abs(distanceX);
        }
    }
}
于 2010-04-16T19:51:34.933 に答える
178

この問題を解決する方法について手がかりを与えてくれた Joel に感謝します。

同じ効果を得るために、コードを単純化しました ( GestureDetectorは必要ありません)。

public class VerticalScrollView extends ScrollView {
    private float xDistance, yDistance, lastX, lastY;

    public VerticalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @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);
    }
}
于 2011-10-09T13:12:27.130 に答える
60

もっと簡単な解決策を見つけたと思いますが、これだけが (親の) ScrollView の代わりに ViewPager のサブクラスを使用します。

UPDATE 2013-07-16 : 同様にオーバーライドを追加しましたonTouchEvent。YMMV.

public class UninterceptableViewPager extends ViewPager {

    public UninterceptableViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        boolean ret = super.onInterceptTouchEvent(ev);
        if (ret)
            getParent().requestDisallowInterceptTouchEvent(true);
        return ret;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        boolean ret = super.onTouchEvent(ev);
        if (ret)
            getParent().requestDisallowInterceptTouchEvent(true);
        return ret;
    }
}

これは、android.widget.Gallery の onScroll() で使用される手法に似ています。これについては、Google I/O 2013 のプレゼンテーションWriting Custom Views for Androidでさらに説明されています。

2013 年 12 月 10 日更新: 同様のアプローチは、Kirill Grouchnikov の (当時の) Android Market アプリに関する投稿でも説明されています。

于 2012-04-24T09:15:43.453 に答える
14

1 つの ScrollView がフォーカスを取り戻し、もう 1 つの ScrollView がフォーカスを失うことがあることがわかりました。scrollView フォーカスの 1 つだけを付与することで、これを防ぐことができます。

    scrollView1= (ScrollView) findViewById(R.id.scrollscroll);
    scrollView1.setAdapter(adapter);
    scrollView1.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            scrollView1.getParent().requestDisallowInterceptTouchEvent(true);
            return false;
        }
    });
于 2012-11-27T20:10:19.310 に答える
8

私にはうまくいきませんでした。変更したところ、スムーズに動作するようになりました。興味のある方はどうぞ。

public class ScrollViewForNesting extends ScrollView {
    private final int DIRECTION_VERTICAL = 0;
    private final int DIRECTION_HORIZONTAL = 1;
    private final int DIRECTION_NO_VALUE = -1;

    private final int mTouchSlop;
    private int mGestureDirection;

    private float mDistanceX;
    private float mDistanceY;
    private float mLastX;
    private float mLastY;

    public ScrollViewForNesting(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);

        final ViewConfiguration configuration = ViewConfiguration.get(context);
        mTouchSlop = configuration.getScaledTouchSlop();
    }

    public ScrollViewForNesting(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public ScrollViewForNesting(Context context) {
        this(context,null);
    }    


    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {      
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mDistanceY = mDistanceX = 0f;
                mLastX = ev.getX();
                mLastY = ev.getY();
                mGestureDirection = DIRECTION_NO_VALUE;
                break;
            case MotionEvent.ACTION_MOVE:
                final float curX = ev.getX();
                final float curY = ev.getY();
                mDistanceX += Math.abs(curX - mLastX);
                mDistanceY += Math.abs(curY - mLastY);
                mLastX = curX;
                mLastY = curY;
                break;
        }

        return super.onInterceptTouchEvent(ev) && shouldIntercept();
    }


    private boolean shouldIntercept(){
        if((mDistanceY > mTouchSlop || mDistanceX > mTouchSlop) && mGestureDirection == DIRECTION_NO_VALUE){
            if(Math.abs(mDistanceY) > Math.abs(mDistanceX)){
                mGestureDirection = DIRECTION_VERTICAL;
            }
            else{
                mGestureDirection = DIRECTION_HORIZONTAL;
            }
        }

        if(mGestureDirection == DIRECTION_VERTICAL){
            return true;
        }
        else{
            return false;
        }
    }
}
于 2014-03-05T13:58:55.623 に答える
6

Neevek のおかげで彼の答えはうまくいきましたが、ユーザーが水平ビュー (ViewPager) を水平方向にスクロールし始めたときに垂直スクロールをロックしません。 . Neevak のコードにわずかな変更を加えて修正しました。

private float xDistance, yDistance, lastX, lastY;

int lastEvent=-1;

boolean isLastEventIntercepted=false;
@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(isLastEventIntercepted && lastEvent== MotionEvent.ACTION_MOVE){
                return false;
            }

            if(xDistance > yDistance )
                {

                isLastEventIntercepted=true;
                lastEvent = MotionEvent.ACTION_MOVE;
                return false;
                }


    }

    lastEvent=ev.getAction();

    isLastEventIntercepted=false;
    return super.onInterceptTouchEvent(ev);

}
于 2013-11-07T18:28:09.183 に答える
5

これは最終的にサポート v4 ライブラリNestedScrollViewの一部になりました。したがって、私が推測するほとんどの場合、ローカルハックはもう必要ありません。

于 2015-10-18T08:27:07.600 に答える
1

Neevek のソリューションは、3.2 以降を実行しているデバイスでは Joel のソリューションよりもうまく機能します。Android にはバグがあり、scollview 内でジェスチャ検出器を使用すると java.lang.IllegalArgumentException: pointerIndex out of range が発生します。問題を再現するには、Joel が提案したようにカスタム scollview を実装し、内部にビュー ページャーを配置します。ある方向 (左/右) にドラッグ (図を持ち上げないでください) してから反対方向にドラッグすると、クラッシュが発生します。また Joel のソリューションでは、指を斜めに動かしてビュー ページャーをドラッグすると、ビュー ページャーのコンテンツ ビュー領域から指が離れると、ページャーは元の位置に戻ります。これらの問題はすべて、それ自体がスマートで簡潔なコードの一部である Joel の実装よりも、Android の内部設計またはその欠如に関係しています。

http://code.google.com/p/android/issues/detail?id=18990

于 2013-02-01T20:53:32.540 に答える