I am making an android launcher and I want to make the wallpaper scroll when the page scroll so I add a onPageChangeListener to mViewPager and change the wallpaper offsets
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int p1, float p2, int p3) {
}
#Override
public void onPageSelected(int p1) {
WallpaperManager.getInstance(c).setWallpaperOffsets(v.getWindowToken(),(float)p1/(myPageItemsCount-1), 0);
}
#Override
public void onPageScrollStateChanged(int p1) {
}
});
The problem is that I want the wallpaper to smooth scroll when the page changed but in my above code , it will directly change the wallpaper to the corresponding position , please help.
Here's what I did and it works like a charm:
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
WallpaperManager.getInstance(getBaseContext()).setWallpaperOffsets(pager.getWindowToken(), (float) (position + positionOffset) / (myPageItemsCount-1), 0);
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
Related
I have a viewpager with left and right arrows. I want to hide left arrow when the first position of a ViewPager and hide right arrow when the last position of a ViewPager visible.
I have referred this solution: How to get position of first and last position of viewpager?
In my view pager I have 3 visible pages at a time. For this I have used getPageWidth to 0.33f :
But it did not work as expected for me.
My code :
vpPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position == (vpPager.getAdapter().getCount())-1) {
right.setVisibility(View.INVISIBLE);
} else {
right.setVisibility(View.VISIBLE);
}
if (position == 0) {
left.setVisibility(View.INVISIBLE);
} else {
left.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
In XML I have set visibility gone for both arrows.
Any help will be appreciatable. Thank you!
To find out current page of ViewPager use ViewPager.getCurrentItem()
Here is a code sample
mViewPager.addOnPageChangeListener(new CustomViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
int currentItem = vpPager.getCurrentItem();
if (currentItem == (vpPager.getAdapter().getCount()-1)) {
right.setVisibility(View.INVISIBLE);
} else {
right.setVisibility(View.VISIBLE);
}
if (currentItem == 0) {
left.setVisibility(View.INVISIBLE);
} else {
left.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
In order to make it work, I would use onPageScrolled instead of onPageSelected since the later one is not called right after the ViewPager is initialised and you can keep the buttons visible in the xml file. It would look like this:
mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
if (position == 0) {
left.setVisibility(View.INVISIBLE);
} else {
left.setVisibility(View.VISIBLE);
}
if (position == adapter.getCount() - 1) {
right.setVisibility(View.INVISIBLE);
} else {
right.setVisibility(View.VISIBLE);
}
}
});
The next and previous buttons are set to work like this:
left.setOnClickListener((v) -> mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1, true));
right.setOnClickListener((v) -> mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1, true));
Also, using onPageScrolled you can create a nice fade-in/fade-out animation for the buttons to stop them from appearing suddenly on the screen.
The following solution is working fine with me.
In order to know last position:
For your case, you cannot get last position '6' from onPageSelected(int position). If you got position totalNumberofPages - numberOfVisiblePagesAtATime, last page is already visible on screen.
For eg , 7-3 = 4 (If you got position 4, it means last page position 6 is already on screen.)
In order to know first position:
you cannot check in onPageChangeListener(). Because this will not call in first time launch.
You need to INVISIBLE your left arrow after viewPager setup. Then in onPageChangeListener call, VISIBLE again.
private int myImagePosition = -1; // class level variable with default value -1.
set visibility of imageView when user click on next or previous
buttons.
myImageViewViewPagerPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (myImagePosition > 0) {
myImagePosition = myImagePosition - 3;
setNextPreviousArrowVisibility();
}
myViewPagerPlanDetailBroucher.setCurrentItem(myImagePosition);
}
});
myImageViewViewPagerNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (myImagePosition < myBroucherDataArrayList.size() - 1) {
myImagePosition = myImagePosition + 3;
setNextPreviousArrowVisibility();
}
myViewPagerPlanDetailBroucher.setCurrentItem(myImagePosition);
}
});
private void setNextPreviousArrowVisibility() {
if (myImagePosition > 3) {
myImageViewViewPagerPrevious.setVisibility(View.VISIBLE);
} else {
myImageViewViewPagerPrevious.setVisibility(View.INVISIBLE);
}
if (myImagePosition > -1 && myImagePosition < myArrayList.size() - 1) {
myImageViewViewPagerNext.setVisibility(View.VISIBLE);
} else {
myImageViewViewPagerNext.setVisibility(View.INVISIBLE);
}
}
im used this libarary https://github.com/47deg/android-swipelistview
in project im want row only swipe to left and not allow swipe rows
with wiche other and when clicked row not swipeing and open new Activity
public class Aragh extends Activity {
SwipeListView swipelistview;
ItemAdapter adapter;
List<ItemRow> itemData;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aragh);
swipelistview=(SwipeListView)findViewById(R.id.example_swipe_lv_list);
itemData=new ArrayList<ItemRow>();
adapter=new ItemAdapter(this,R.layout.custom_row,itemData);
swipelistview.setSwipeListViewListener(new BaseSwipeListViewListener() {
#Override
public void onOpened(int position, boolean toRight) {
}
#Override
public void onClosed(int position, boolean fromRight) {
}
#Override
public void onListChanged() {
}
#Override
public void onMove(int position, float x) {
}
#Override
public void onStartOpen(int position, int action, boolean right) {
Log.d("swipe", String.format("onStartOpen %d - action %d", position, action));
}
#Override
public void onStartClose(int position, boolean right) {
Log.d("swipe", String.format("onStartClose %d", position));
}
#Override
public void onClickFrontView(int position) {
Log.d("swipe", String.format("onClickFrontView %d", position));
swipelistview.openAnimate(position); //when you touch front view it will open
}
#Override
public void onClickBackView(int position) {
Log.d("swipe", String.format("onClickBackView %d", position));
swipelistview.closeAnimate(position);//when you touch back view it will close
}
#Override
public void onDismiss(int[] reverseSortedPositions) {
}
});
//These are the swipe listview settings. you can change these
//setting as your requirement
swipelistview.setSwipeMode(SwipeListView.SWIPE_MODE_RIGHT); // there are five swiping modes
swipelistview.setSwipeActionLeft(SwipeListView.SWIPE_ACTION_DISMISS); //there are four swipe actions
swipelistview.setSwipeActionRight(SwipeListView.SWIPE_ACTION_DISMISS);
swipelistview.setOffsetLeft(convertDpToPixel(0f)); // left side offset
swipelistview.setOffsetRight(convertDpToPixel(80f)); // right side offset
swipelistview.setAnimationTime(500); // Animation time
swipelistview.setSwipeOpenOnLongPress(false); // enable or disable SwipeOpenOnLongPress
swipelistview.setAdapter(adapter);
for(int i=0;i<10;i++)
{
itemData.add(new ItemRow("Swipe Item"+i,getResources().getDrawable(R.drawable.ic_launcher) ));
}
adapter.notifyDataSetChanged();
}
public int convertDpToPixel(float dp) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return (int) px;
}
}
I recommend doing it in XML.
in your SwipeListView tag add
swipe:swipeMode="left"
it locks your swipe mode to the left.
you can choose - left / right / both .
You just need to put swipe:swipeMode="left" inside <....SwipeListView /> in your xml layout to allow swiping only in left direction
In my android application i have used viewpager, but i need to change the view of viewpager as like below
My Adapter
pager.setPageTransformer(false, new ViewPager.PageTransformer() {
#Override
public void transformPage(View page, float position) {
// do transformation here
// page.setRotationY(position * -40);
final float normalizedposition = Math.abs(Math.abs(position) - 1);
page.setScaleX(normalizedposition / 2 + 0.4f);
page.setScaleY(normalizedposition / 2 + 0.4f);
}
});
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
pager.setCurrentItem(position);
}
#Override
public void onPageScrolled(int position, float positionOffset,
int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
can anyone suggest how to achieve this
All answers are most welcome
Is it possible to have 2 ViewPagers that simultaniously scroll together, if I start scrolling on one, the other does the exact same scrolling behaviour. Or should I implement somthing other than a ViewPager.
thank you
The solution that worked best for me was to pass MotionEvent in OnTouchListener between ViewPager instances. Tried fake dragging but it was always laggy and buggy (tried the solution from this thread too - didn't work) - I needed a smooth, parallax-like effect.
So, my advice is to implement a View.OnTouchListener. The MotionEvent has to be scaled to compensate for the difference in width.
public class SyncScrollOnTouchListener implements View.OnTouchListener {
private final View syncedView;
public SyncScrollOnTouchListener(#NonNull View syncedView) {
this.syncedView = syncedView;
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
MotionEvent syncEvent = MotionEvent.obtain(motionEvent);
float width1 = view.getWidth();
float width2 = syncedView.getWidth();
//sync motion of two view pagers by simulating a touch event
//offset by its X position, and scaled by width ratio
syncEvent.setLocation(syncedView.getX() + motionEvent.getX() * width2 / width1,
motionEvent.getY());
syncedView.onTouchEvent(syncEvent);
return false;
}
}
Then set it to your ViewPager
sourcePager.setOnTouchListener(new SyncScrollOnTouchListener(targetPager));
Note that this solution will only work if both pagers have the same orientation. If you need it to work for different orientations - adjust syncEvent Y coordinate instead of X.
There is one more issue that we need to take into account - minimum fling speed and distance that can cause just one pager to change page.
It can be easily fixed by adding an OnPageChangeListener to our pager
sourcePager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
//no-op
}
#Override
public void onPageSelected(int position) {
targetPager.setCurrentItem(position, true);
}
#Override
public void onPageScrollStateChanged(int state) {
//no-op
}
});
You can give each an OnPageChangeListsner and implement onPageScrolled (and maybe also onPageSelected for when you change pages without scrolling). Since the logic will be the same, we can write a class for this:
public class ViewPagerScrollSync implements ViewPager.OnPageChangeListener {
private ViewPager actor; // the one being scrolled
private ViewPager target; // the one that needs to be scrolled in sync
public ViewPagerScrollSync(ViewPager actor, ViewPager target) {
this.actor = actor;
this.target = target;
actor.setOnPageChangeListener(this);
}
#Override
public void onPageScrollStateChanged(int state) {
if (actor.isFakeDragging()) {
return;
}
if (state == ViewPager.SCROLL_STATE_DRAGGING) {
// actor has begun a drag
target.beginFakeDrag();
} else if (state == ViewPager.SCROLL_STATE_IDLE) {
// actor has finished settling
target.endFakeDrag();
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (actor.isFakeDragging()) {
return;
}
if (target.isFakeDragging()) {
// calculate drag amount in pixels.
// i don't have code for this off the top of my head, but you'll probably
// have to store the last position and offset from the previous call to
// this method and take the difference.
float dx = ...
target.fakeDragBy(dx);
}
}
#Override
public void onPageSelected(int position) {
if (actor.isFakeDragging()) {
return;
}
// Check isFakeDragging here because this callback also occurs when
// the user lifts his finger on a drag. If it was a real drag, we will
// have begun a fake drag of the target; otherwise it was probably a
// programmatic change of the current page.
if (!target.isFakeDragging()) {
target.setCurrentItem(position);
}
}
}
Then in your Activity/Fragment, you would do this:
ViewPager pager1 = ...
ViewPager pager2 = ...
ViewPagerScrollSync sync1 = new ViewPagerScrollSync(pager1, pager2);
ViewPagerScrollSync sync2 = new ViewPagerScrollSync(pager2, pager1);
you will need to keep an eye on your positions to avoid IndexOutOfBounds errors. Generally:
viewPager1.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
viewPager2.setCurrentItem(position);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int state) {
// TODO Auto-generated method stub
}
});
This will work assuming that both ViewPagers have the same number of items. Otherwise, you will need to track your positions to synchronize the behavior of both pagers.
To clarify: if your Adapters have a different number of items or you don't want both pagers to behave exactly the same, you will need to check the position of viewPager1 in the onPageSelected() method and then adjust the position to pass to the setCurrentItem() method of viewPager2
Drop this class in your project
import androidx.viewpager.widget.ViewPager;
/**
* Sync Scroll 2 View Pager
*/
public class SyncScrollOnTouchListener implements ViewPager.OnPageChangeListener {
private ViewPager master;
private ViewPager slave;
private int mScrollState = ViewPager.SCROLL_STATE_IDLE;
public SyncScrollOnTouchListener(ViewPager master, ViewPager slave){
this.master = master;
this.slave = slave;
}
#Override
public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
return;
}
this.slave.scrollTo(this.master.getScrollX()*
this.slave.getWidth()/
this.master.getWidth(), 0);
}
#Override
public void onPageSelected(final int position) {
}
#Override
public void onPageScrollStateChanged(final int state) {
mScrollState = state;
if (state == ViewPager.SCROLL_STATE_IDLE) {
this.slave.setCurrentItem(this.master
.getCurrentItem(), false);
}
}
}
Usage:
Now you can sync page change of View Pages
masterPager.addOnPageChangeListener(newSyncScrollOnTouchListener(masterPager,slavePager));
//Sync Scroll of Pages
leftPanelPager.addOnPageChangeListener(new SyncScrollOnTouchListener(leftPanelPager,rightPanelPager));
rightPanelPager.addOnPageChangeListener(new SyncScrollOnTouchListener(rightPanelPager,leftPanelPager));
I'm trying to synchronize two ViewPagers, as apparently have quite a lot of people before me, and I've got as far as this:
private ViewPager mNavPager;
private ViewPager mMainPager;
private final OnPageChangeListener mNavPagerListener = new OnPageChangeListener() {
private boolean mNavDragging;
private int mScrollPosition;
#Override
public void onPageSelected(int position) {
mScrollPosition = position;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if(mNavDragging)
mMainPager.scrollTo(positionOffsetPixels, 0);
}
#Override
public void onPageScrollStateChanged(int state) {
switch(state) {
case ViewPager.SCROLL_STATE_DRAGGING:
case ViewPager.SCROLL_STATE_SETTLING:
mNavDragging = true;
break;
case ViewPager.SCROLL_STATE_IDLE:
mNavDragging = false;
break;
}
}
};
private OnPageChangeListener mMainPagerListener = new OnPageChangeListener() {
private boolean mMainDragging;
private int mScrollPosition;
#Override
public void onPageSelected(int position) {
mScrollPosition = position;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if(mMainDragging)
mNavPager.scrollTo(positionOffsetPixels, 0);
}
#Override
public void onPageScrollStateChanged(int state) {
switch(state) {
case ViewPager.SCROLL_STATE_DRAGGING:
case ViewPager.SCROLL_STATE_SETTLING:
mMainDragging = true;
break;
case ViewPager.SCROLL_STATE_IDLE:
mMainDragging = false;
break;
}
}
};
If either one is scrolled manually, the other is slaved to it using the scroll state property. It works beautifully till the items reach their final position; at this point, the slaved pager flicks instantly back to the previously selected item, as though the scrolling hadn't taken place.
I have tried calling ViewPager#setCurrentItem(mScrolledPosition) with a variety of different logic constraints but that doesn't work either, though it does occasionally make it worse. I feel as though there must be something that can be done with that but I'm not sure what.
How can I get the slaved pager to remain in the correct position?
I solved this problem in a much easier (and cleaner) way using the OnPageChangeListener:
mViewPager1.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
private int mScrollState = ViewPager.SCROLL_STATE_IDLE;
#Override
public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
return;
}
mViewPager2.scrollTo(mViewPager1.getScrollX(), mViewPager2.getScrollY());
}
#Override
public void onPageSelected(final int position) {
}
#Override
public void onPageScrollStateChanged(final int state) {
mScrollState = state;
if (state == ViewPager.SCROLL_STATE_IDLE) {
mViewPager2.setCurrentItem(mViewPager1.getCurrentItem(), false);
}
}
});
mViewPager2.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
private int mScrollState = ViewPager.SCROLL_STATE_IDLE;
#Override
public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
return;
}
mViewPager1.scrollTo(mViewPager2.getScrollX(), mViewPager1.getScrollY());
}
#Override
public void onPageSelected(final int position) {
}
#Override
public void onPageScrollStateChanged(final int state) {
mScrollState = state;
if (state == ViewPager.SCROLL_STATE_IDLE) {
mViewPager1.setCurrentItem(mViewPager2.getCurrentItem(), false);
}
}
});
I have Solved the problem without utilizing the Listener.
So you can use the listener for some other stuff and will make code look cleaner.
I know its a question asked a long ago. I was searching for a solution and solved it myself.
This is how my Custom ViewPager code is
public class CustomPager extends ViewPager {
CustomPager mCustomPager;
private boolean forSuper;
public CustomPager(Context context) {
super(context);
}
public CustomPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
if (!forSuper) {
mCustomPager.forSuper(true);
mCustomPager.onInterceptTouchEvent(arg0);
mCustomPager.forSuper(false);
}
return super.onInterceptTouchEvent(arg0);
}
#Override
public boolean onTouchEvent(MotionEvent arg0) {
if (!forSuper) {
mCustomPager.forSuper(true);
mCustomPager.onTouchEvent(arg0);
mCustomPager.forSuper(false);
}
return super.onTouchEvent(arg0);
}
public void setViewPager(CustomPager customPager) {
mCustomPager = customPager;
}
public void forSuper(boolean forSuper) {
this.forSuper = forSuper;
}
#Override
public void setCurrentItem(int item, boolean smoothScroll) {
if (!forSuper) {
mCustomPager.forSuper(true);
mCustomPager.setCurrentItem(item, smoothScroll);
mCustomPager.forSuper(false);
}
super.setCurrentItem(item, smoothScroll);
}
#Override
public void setCurrentItem(int item) {
if (!forSuper) {
mCustomPager.forSuper(true);
mCustomPager.setCurrentItem(item);
mCustomPager.forSuper(false);
}
super.setCurrentItem(item);
}
}
And you have to set pagers like this before adapter is set and just after getting reference using the ID.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
backPager=(CustomPager) findViewById(R.id.BackPager);
frontPager = (CustomPager) findViewById(R.id.frontPager);
frontPager.setViewPager(backPager);
backPager.setViewPager(frontPager);
backPager.setAdapter(your Adapter);
frontPager.setAdapter(your Adapter);
}
Must set ViewPagers before assigning adapter.
I had a similar issue, also needed to combine my syncing with animations in PageTransformer.
Originally posted this answer here: https://stackoverflow.com/a/43638796/2867886
But I will paste it here for convenience.
The solution that worked best for me was to pass MotionEvent in OnTouchListener between ViewPager instances. Tried fake dragging but it was always laggy and buggy - I needed a smooth, parallax-like effect.
So, my advice is to implement a View.OnTouchListener. The MotionEvent has to be scaled to compensate for the difference in width.
public class SyncScrollOnTouchListener implements View.OnTouchListener {
private final View syncedView;
public SyncScrollOnTouchListener(#NonNull View syncedView) {
this.syncedView = syncedView;
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
MotionEvent syncEvent = MotionEvent.obtain(motionEvent);
float width1 = view.getWidth();
float width2 = syncedView.getWidth();
//sync motion of two view pagers by simulating a touch event
//offset by its X position, and scaled by width ratio
syncEvent.setLocation(syncedView.getX() + motionEvent.getX() * width2 / width1,
motionEvent.getY());
syncedView.onTouchEvent(syncEvent);
return false;
}
}
Then set it to your ViewPager
sourcePager.setOnTouchListener(new SyncScrollOnTouchListener(targetPager));
Note that this solution will only work if both pagers have the same orientation. If you need it to work for different orientations - adjust syncEvent Y coordinate instead of X.
There is one more issue that we need to take into account - minimum fling speed and distance that can cause just one pager to change page.
It can be easily fixed by adding an OnPageChangeListener to our pager
sourcePager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
//no-op
}
#Override
public void onPageSelected(int position) {
targetPager.setCurrentItem(position, true);
}
#Override
public void onPageScrollStateChanged(int state) {
//no-op
}
});
This does everything right except it sometimes misses very quick flicks on the slaved view. For some reason including fake drag events during the settling phase causes real problems, though.
private ViewPager mNavPager;
private ViewPager mMainPager;
private final OnPageChangeListener mNavPagerListener = new OnPageChangeListener() {
private int mLastScrollPosition;
private int mLastPagePosition;
#Override
public void onPageSelected(int position) {
mLastPagePosition = position;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if(mMainPager.isFakeDragging()) {
int absoluteOffsetPixels = positionOffsetPixels;
if(mLastPagePosition!=position) {
absoluteOffsetPixels += (position - mLastPagePosition) * mMainPager.getWidth();
mLastPagePosition = position;
}
Log.d(TAG, "fake nav drag by " + (mLastScrollPosition - absoluteOffsetPixels));
mMainPager.fakeDragBy(mLastScrollPosition - absoluteOffsetPixels);
mLastScrollPosition = positionOffsetPixels;
}
}
#Override
public void onPageScrollStateChanged(int state) {
if(!mNavPager.isFakeDragging()) {
switch(state) {
case ViewPager.SCROLL_STATE_DRAGGING:
if(!mMainPager.isFakeDragging())
mMainPager.beginFakeDrag();
break;
case ViewPager.SCROLL_STATE_SETTLING:
case ViewPager.SCROLL_STATE_IDLE:
if(mMainPager.isFakeDragging()) {
mMainPager.endFakeDrag();
mLastScrollPosition = 0;
}
break;
}
}
}
};
private OnPageChangeListener mMainPagerListener = new OnPageChangeListener() {
private int mLastScrollPosition;
private int mLastPagePosition;
#Override
public void onPageSelected(int position) {
mLastPagePosition = position;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if(mNavPager.isFakeDragging()) {
int absoluteOffsetPixels = positionOffsetPixels;
if(mLastPagePosition!=position) {
absoluteOffsetPixels += (position - mLastPagePosition) * mMainPager.getWidth();
mLastPagePosition = position;
}
Log.d(TAG, "fake nav drag by " + (mLastScrollPosition - absoluteOffsetPixels));
mNavPager.fakeDragBy(mLastScrollPosition - absoluteOffsetPixels);
mLastScrollPosition = positionOffsetPixels;
}
}
#Override
public void onPageScrollStateChanged(int state) {
if(!mMainPager.isFakeDragging()) {
switch(state) {
case ViewPager.SCROLL_STATE_DRAGGING:
if(!mNavPager.isFakeDragging())
mNavPager.beginFakeDrag();
break;
case ViewPager.SCROLL_STATE_SETTLING:
case ViewPager.SCROLL_STATE_IDLE:
if(mNavPager.isFakeDragging()) {
mNavPager.endFakeDrag();
mLastScrollPosition = 0;
}
break;
}
}
}
};
EDIT
I now believe this to be impossible without some fairly substantial custom code. The reason is essentially that both ViewPagers have a VelocityTracker inside, which controls scrolling. Since the MotionEvents being passed in may not be passed to the VelocityTracker at the same relative times for each pager, the trackers will occasionally reach different conclusions about how to react.
However, it is possible to use a modified PagerTitleStrip to get precise tracking of a ViewPager, and to transfer touch events captured by the strip directly to the ViewPager.
The source for PagerTitleStrip is here.
Broadly, what needs to be done to make this work is as follows: replace mPrevText, mCurrText and mNextText with views of the type you want to use; remove the onAttachedToWindow() and onDetachedFromWindow() functions; remove calls to the PagerAdapter that deal with dataset observers, and add an OnTouchListener to the modified strip that fake drags the main pager. You'll also need to add the modified title strip as an OnPageChangeListener to the ViewPager since the internal listeners aren't visible outside the package.
Is this a gigantic pain? Yes. But it works. I will write it up in more detail soon.
With help from all other answers I've created a Class so it easily can be implemented.
public class OnPageChangeListernerSync implements ViewPager.OnPageChangeListener {
private ViewPager master;
private ViewPager slave;
private int mScrollState = ViewPager.SCROLL_STATE_IDLE;
public OnPageChangeListernerSync(ViewPager master, ViewPager slave){
this.master = master;
this.slave = slave;
}
#Override
public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
return;
}
this.slave.scrollTo(this.master.getScrollX()*
this.slave.getWidth()/
this.master.getWidth(), 0);
}
#Override
public void onPageSelected(final int position) {
}
#Override
public void onPageScrollStateChanged(final int state) {
mScrollState = state;
if (state == ViewPager.SCROLL_STATE_IDLE) {
this.slave.setCurrentItem(this.master
.getCurrentItem(), false);
}
}
}
...
// In your activity
this.upperPager.addOnPageChangeListener(new OnPageChangeListernerSync(this.upperPager, this.lowerPager));
this.lowerPager.addOnPageChangeListener(new OnPageChangeListernerSync(this.lowerPager, this.upperPager));
All the Answers are approximately currect in some situation. Here I am giving one more answer which will use to slide both the ViewPagers simultaneously whether there size is same or not:
viewPagerBanner.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
private int scrollState = ViewPager.SCROLL_STATE_IDLE;
// Indicates that the pager is in an idle, settled state.
// The current page is fully in view and no animation is in progress.
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
if (scrollState == ViewPager.SCROLL_STATE_IDLE) {
return;
}
viewPagerTitle.scrollTo(viewPagerBanner.getScrollX()*
viewPagerTitle.getWidth()/
viewPagerBanner.getWidth(), 0);
// We are not interested in Y axis position
}
#Override
public void onPageSelected(int position) {}
#Override
public void onPageScrollStateChanged(int state) {
scrollState = state;
if (state == ViewPager.SCROLL_STATE_IDLE) {
viewPagerTitle.setCurrentItem(viewPagerBanner.getCurrentItem(), false);
}
}
});