Search code examples
androidnavigationandroid-gallery

Navigate only one View by gesture on Gallery


I have a Gallery that each current item matchs the display dimensions. I want when the user try to "throw" the views to any side, instead of the automatic scrolling, I want to go just to the next View.

How can I do that?


Solution

  • Check this snippet. It uses no scrolling constants, instead it relies on scolling key event to handle for different resolutions.

    private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2){
        return e2.getX() > e1.getX();
    }
    
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY){
        int kEvent;
        if(isScrollingLeft(e1, e2)){ //Check if scrolling left
            kEvent = KeyEvent.KEYCODE_DPAD_LEFT;
        }
        else{ //Otherwise scrolling right
            kEvent = KeyEvent.KEYCODE_DPAD_RIGHT;
        }
        onKeyDown(kEvent, null);
        return true;  
    }
    

    This piece of code belongs to a galleryView model which extends Gallery and its layout looks like this

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="180dp">
        <com.example.android.GalleryView
            android:id="@+id/gallery"
            android:layout_width="fill_parent"
            android:layout_height="180dp"
            android:gravity="bottom"
            android:fadingEdge="none"/>
    </LinearLayout>