Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ViewPager center item on screen

I am trying to show a dialog over my screen. And that dialog should have ViewPager in it with FragmentPagerAdapter. Each item in adapter has width set to .7f. What is important to me is that when some item is selected it should be snapped to center of the ViewPager with parts of next and previous fragments visible (exactly as image shows). Unfortunately the default behavior is snap to the left.

Is there any way of achieving it please?

Thank you

(Just if anybody asks: On that picture the ViewPager is not stretched over dialog. In real the dialog matches parent's width and is layouted the way so it doesn't look like it)

screen

like image 311
bakua Avatar asked Dec 05 '22 22:12

bakua


1 Answers

Just in case anyone is looking for the same thing, I've come to solution: Simply set left and right padding to ViewPager and then set clipToPadding to false. That will result into one fragment to be centered and pieces of neighbor fragments in sides as it is in picture. Then to add space between fragments use viewPager.setPageMargin(); in code.

That's it :)

EDIT://

Here is some sample code

<android.support.v4.view.ViewPager
 android:id="@+id/viewPager"
 android:clipToPadding="false"
 android:paddingLeft="40dp"
 android:paddingRight="40dp"
 android:layout_width="match_parent"
 android:layout_height="match_parent" />

ClipToPadding=false ensures that fragments will be drawn even when they are positioned out of the viewPager's content area.

And then in code add spaces between viewPager's items:

mViewPager.setPageMargin(100);

Please note that setPageMargin takes number of pixels as parameter, not number of display points. You probably should convert some dp value to pixels to have correct spacing across all devices. This method should work fine:

public static float dipToPixels(Context context, float dipValue) {
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics);
}
like image 66
bakua Avatar answered Dec 27 '22 07:12

bakua