Tag Archives: override

Android : compatibility between ViewPager and SlidingMenu

You already may have encountered “bug” by using a Viewpager and a SlidingMenu at the same time :

this bug is simply while sliding viewpager… the sliding menu “takes” the event.

 

How to fix it?

In fact, it is very simple. First of all, make an object (your fragment, activity…), create a method which will take one integer (native one, not the Object ;p )

In it, you can simply check if the index is equal to 0 (or the maximum if you were using a right menu >> according to your code, but here, I will only make it compatible with left. Add now a simple if else statement. If the index is 0 then enable the menu, otherwise disable it.

For example:


public class SlidingViewPagerFragmentActivity extends SlidingFragmentActivity{
  public void setViewPagerSelected(int index){
    //in this example, I also check for the screen
    //which is currently selected
    if(index == 0 && this.findViewById(R.id.mobile) != null){
      this.getSlidingMenu().setSlidingEnabled(true);
    }else{
      this.getSlidingMenu().setSlidingEnabled(false);
    }
  }
}

Now that we have a perfectly working checking method, you can now implements a OnPageChangeListener in your activity/fragment/whatever… (from the …view.ViewPager package)

Once done, you will have to override the onPageSelected(int index) method. In this one, call your Object which manage the SlidingMenu (in my own code, I made an object override SherlockFragmentActivity, implements the first method in it and then, my activities simply override my Activity with this method. And to finish (last little thing), register your Object in the :
yourpager.setOnPageChangeListener()
//note that if you use the ViewPagerIndicator, you will have to register your Object
//in the indicator ;)

For instance (in a SherlockFragment):


public class FragmentExample extends SherlockFragment{
  @Override
  public void onPageSelected(int index) {
    if(getSherlockActivity() instanceof SlidingViewPagerFragmentActivity){
      ((SlidingViewPagerFragmentActivity)getSherlockActivity()).setViewPagerSelected(index);
    }
  }
}

And voila 😉