Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ViewPager padding/margin between page fragments

Android Market/Google Music seem to be able to have a gap of some sort between the different fragments that are contained in the ViewPager.

Any idea how this is done? Adding margin/padding to the actual fragment view doesn't work, because the view still needs to occupy the entire width of the screen. The 'gap' is only visible when swiping the ViewPager.

like image 455
psychotik Avatar asked Sep 08 '11 05:09

psychotik


4 Answers

In Support Package, r4 you can use these methods:

setPageMargin(int marginPixels)
setPageMarginDrawable(Drawable)
setPageMarginDrawable(int)

in ViewPager class.

I don't know why this doesn't have equivalent in XML :-(

If you need use dip unit you can use this method:

public static int convertDip2Pixels(Context context, int dip) {
    return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, context.getResources().getDisplayMetrics());
}
like image 118
ATom Avatar answered Nov 19 '22 04:11

ATom


Hoping this might help someone with a ViewPager and page margins.

I wanted to have a ViewPager is a CardView and had issues with the padding and the margin between the viewpager pages. The setPageMargin did not work for me at all. I had to use the following:

int pagerPadding = 16;
pager.setClipToPadding(false);
pager.setPadding(pagerPadding, 0, pagerPadding, 0);

This allow the pages to be very close together.

Example of the viewpager with a small margin between the pages.

like image 22
Ray Hunter Avatar answered Nov 19 '22 02:11

Ray Hunter


  viewPager.setPageMargin(dpToPx(10)); 
  // replace 10 with the value you want for margin in dp. 


 public int dpToPx(int dp) {
    DisplayMetrics displayMetrics = getActivity().getResources().getDisplayMetrics();
    return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
 }
like image 7
Anirudh Avatar answered Nov 19 '22 03:11

Anirudh


Try This .

    ViewPager viewPager = (ViewPager) findViewById(R.id.h_view_pager);
    viewPager.setClipToPadding(false);
    viewPager.setPadding(60, 0, 60, 0);
    viewPager.setPageMargin(20);
    ImagePagerAdapter adapter = new ImagePagerAdapter();
    viewPager.setOffscreenPageLimit(adapter.getCount());
    viewPager.setAdapter(adapter);
like image 5
Rambabu Avatar answered Nov 19 '22 04:11

Rambabu