13

I have a (Sherlock)FragmentActivity with 2 tabbed fragments. The left fragment is a GridView that displays pictures of an album and the right fragment consists of a ViewPager that is used to view individual pictures. From the left fragment you can scroll through the pictures and select one. Tabbing (or swiping) over to the right fragment will show the picture and because it is a ViewPager you can swipe to the preceding or the next picture.

This works great except that the FragmentActivity wants to intercept the right swipe and move back to the left tab. I would like to prevent the FragmentActivity from intercepting the swipes when I am on the right tab. If I had to disable swiping between tabs altogether it would be satisfactory. I just want the swiping to be dedicated to the current tab and not be used to move between tabs.

The following images indicate the current behavior. The right image shows what happens when I do a swipe to the right. As you can see the left tab starts to appear. I want the swipe to instead apply to the right tab only so that I can swipe between the images without the left tab appearing.

enter image description here

I see solutions to control swiping within a ViewPager but have yet to find a solution to control swiping between tabbed fragments.

Here is the xml for the GridView fragment and the ViewPager fragment:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical">
  <FrameLayout android:id="@android:id/tabcontent"
               android:layout_width="fill_parent"
               android:layout_height="fill_parent">
    <GridView xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/gridview"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:columnWidth="100dip"
              android:gravity="center"
              android:horizontalSpacing="4dip"
              android:numColumns="auto_fit"
              android:stretchMode="columnWidth"
              android:verticalSpacing="4dip" />
  </FrameLayout>
</LinearLayout>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical">

  <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
                                     android:id="@+id/pager"
                                     android:layout_width="fill_parent"
                                     android:layout_height="0px"
                                     android:layout_weight="1"/>
</LinearLayout>

Here a code summary of the ViewPager fragment:

public class FragmentFlash extends SherlockFragment {

   private GestureDetector gestureDetector;
   View.OnTouchListener gestureListener;
   private ViewPager pager = null;
   private int pagerPosition;

   @Override
      public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      pagerPosition = 0;
      // Gesture detection
      gestureDetector = new GestureDetector(new MyGestureDetector());
      gestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
               return gestureDetector.onTouchEvent(event);
            }
         };
      }

   @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                               Bundle savedInstanceState) {
      View v = inflater.inflate(R.layout.flash, container, false);
      pager = (ViewPager) v.findViewById(R.id.pager);
      pager.setOnTouchListener(gestureListener);
      return v;
   }

   class MyGestureDetector extends SimpleOnGestureListener {
      private static final int SWIPE_MIN_DISTANCE = 10;
      private static final int SWIPE_MAX_OFF_PATH = 250;
      private static final int SWIPE_THRESHOLD_VELOCITY = 50;

      @Override
         public boolean onDown(MotionEvent e) {
         return true;//false; make onFling work with fragments
      }

      @Override
         public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
         try {
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
               return false;
            else
               // right to left swipe
               if(distanceX > SWIPE_MIN_DISTANCE) {
                  if (pagerPosition < imageUrls.length-1)
                     pager.setCurrentItem(++pagerPosition);
               // left to right swipe
               } else if (distanceX < -SWIPE_MIN_DISTANCE) {
                  if (pagerPosition > 0)
                     pager.setCurrentItem(--pagerPosition);
               }
            return true;
         } catch (Exception e) {
            // nothing
         }
         return false;
      }
   }

   private class ImagePagerAdapter extends PagerAdapter {

      private String[] images;
      private LayoutInflater inflater;

      ImagePagerAdapter(String[] images) {
         this.images = images;
         inflater = mContext.getLayoutInflater();
      }

      @Override
         public void destroyItem(View container, int position, Object object) {
         ((ViewPager) container).removeView((View) object);
      }

      @Override
         public void finishUpdate(View container) {
      }

      @Override
         public int getCount() {
         return images.length;
      }

      @Override
         public Object instantiateItem(View view, int position) {
         final View imageLayout = inflater.inflate(R.layout.item_pager_image, null);
         final ImageView imageView = (ImageView)   imageLayout.findViewById(R.id.image);
         final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);

         byte[] image = ;//get byte array from file at images[position];
         if (null != image) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
            imageView.setImageBitmap(bitmap);
         }
         ((ViewPager) view).addView(imageLayout, 0);

         return imageLayout;
      }

      @Override
         public boolean isViewFromObject(View view, Object object) {
         return view.equals(object);
      }

      @Override
         public void restoreState(Parcelable state, ClassLoader loader) {
      }

      @Override
         public Parcelable saveState() {
         return null;
      }

      @Override
         public void startUpdate(View container) {
      }
   }

   public void pagerPositionSet(int pagerPosition, String[] imageUrls) {
      Log.i(Flashum.LOG_TAG, "FragmentFlash pagerPositionSet: " + pagerPosition);
      if (pagerPosition >= 0)
         this.pagerPosition = pagerPosition;
      if (pager != null) {
         pager.setAdapter(new ImagePagerAdapter(imageUrls));
         pager.setCurrentItem(this.pagerPosition);
      }
   }

}

This is the item_pager_image.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="1dip" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:adjustViewBounds="true"
        android:contentDescription="@string/descr_image" />

    <ProgressBar
        android:id="@+id/loading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:visibility="gone" />

</FrameLayout>
charles young
  • 2,269
  • 2
  • 23
  • 38

2 Answers2

18

Ok, I finally figured this out. Laurence Dawson was on the right track but instead of applying the CustomViewPager to the fragment it needs to be applied to the FragmentActivity. You see, switching between tabs, which is managed by the activity, is also a ViewPager adaptor. Thus, xml for the activity is

<TabHost
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TabWidget
            android:id="@android:id/tabs"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"/>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="0"/>

        <com.Flashum.CustomViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"/>

    </LinearLayout>
</TabHost>

And the custom ViewPager is as suggested except that that the constructor enables it to cause onInterceptTouchEvent to return false. This prevents the FragmentActivity from acting on the swipe so that it can be dedicated to the fragment!

public class CustomViewPager extends ViewPager {

    private boolean enabled;

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.enabled = **false**;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (this.enabled) {
            return super.onTouchEvent(event);
        }

        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (this.enabled) {
            return super.onInterceptTouchEvent(event);
        }

        return false;
    }

    public void setPagingEnabled(boolean enabled) {
        this.enabled = enabled;
    }
}
charles young
  • 2,269
  • 2
  • 23
  • 38
  • "instead of applying the CustomViewPager to the fragment it needs to be applied to the FragmentActivity". I did not state that you need to apply this to the fragment and neither does the link I provided. Your answer just copies code from the link provided which already fully explains how to override the onInterceptTouchEvent to disable swiping. – Ljdawson Jan 27 '13 at 13:44
9

You need to override the onInterceptTouchEvent method for your ViewPager, you can do this by extending ViewPager or visit this link for a great tutorial on adding this:

http://blog.svpino.com/2011/08/disabling-pagingswiping-on-android.html

Ljdawson
  • 12,091
  • 11
  • 45
  • 60
  • 1
    I tried this code and found that it is only for controlling swiping within the ViewPager fragment. It does not prevent the FragmentActivity from trying to swipe between the tabs. In other words, when I swipe to the right not only will MyGestureDetector::onScroll() be called but also the left tab will start to appear on the left side indicating that FragmentActivity is also detecting and processing the swipe. – charles young Nov 01 '12 at 16:37
  • I'm not sure why you even have a gesture detector, the ViewPager handles all of the swiping for you – Ljdawson Nov 01 '12 at 18:06
  • I did that so that I could adjust the sensitivity of swipe. Now with very small swipes I can stay within the right tab. However, with a normal swipe the FragmentActivity detects it and takes over. BTW, I did try disabling my gesture detector and even with the custom ViewPager you referenced it does not help. – charles young Nov 01 '12 at 19:44