Android Viewpager bounces half a page

So, what I'm trying to achieve, the user will open on the first page of the presentation pager, and the presentation pager will bounce to half the second page and return to the first page, indicating that to go to other pages, I was wondering how I can implement this ?

+5
source share
3 answers

You can use the fakeDragBy method to achieve this effect:

viewPager.beginFakeDrag(); viewPager.fakeDragBy(offset); //offset in pixels. viewPager.endFakeDrag(); 

EDIT:

I made a method for this:

 private int animFactor; private ValueAnimator animator = new ValueAnimator(); private void animateViewPager(final ViewPager pager, final int offset, final int delay) { if (!animator.isRunning()) { animator.removeAllUpdateListeners(); animator.removeAllListeners(); //Set animation animator.setIntValues(0, -offset); animator.setDuration(delay); animator.setRepeatCount(1); animator.setRepeatMode(ValueAnimator.RESTART); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { public void onAnimationUpdate(ValueAnimator animation) { Integer value = animFactor * (Integer) animation.getAnimatedValue(); if (!pager.isFakeDragging()) { pager.beginFakeDrag(); } pager.fakeDragBy(value); } }); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { animFactor = 1; } @Override public void onAnimationEnd(Animator animation) { pager.endFakeDrag(); } @Override public void onAnimationRepeat(Animator animation) { animFactor = -1; } }); animator.start(); } } 

Usage example:

 animateViewPager(pager, 10, 1000); 

Edit2: ValueAnimator is a class for the Api 11 level. Also define a pager adapter before calling this method.

+12
source

Adding a note to @Yuraj's answer. Call the method in onWindowFocusChanged with hasFocus==true as follows to avoid indexOutOfBoundsException :

 @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if(hasFocus) { Handler handler = new Handler(); final Runnable r = new Runnable() { public void run() { if(mViewPager.getCurrentItem() == 0) { Context context = Activity_main.this; String filename="Init"; SharedPreferences stats; stats = context.getSharedPreferences(filename, 0); int appOpen = stats.getInt("appOpen", 0); if(appOpen <= 5) { animateViewPager(mViewPager, 10, 300); appOpen += 1; SharedPreferences.Editor editor = stats.edit(); editor.putInt("appOpen", appOpen); editor.commit(); } } } }; handler.postDelayed(r, WAIT_VIEWPAGER_NUDGE); } } 
+1
source

open gradle first and compile:

compile 'me.everything: overscroll-decor-android: 1.0.3'

and your viewpager code:

  viewPager = (ViewPager) findViewById(R.id.walkthrough_pager); OverScrollDecoratorHelper.setUpOverScroll(viewPager); 

link: https://github.com/EverythingMe/overscroll-decor

0
source

Source: https://habr.com/ru/post/1201042/


All Articles