Stefano Cremona
Stefano Cremona

Reputation: 791

ViewPager with items preview

I want to show a ViewPager with all the days of the week with a preview of the following and previous item of the current one. I've tried a lot of solutions suggested from stackoverflow but none of them is working. I don't wont to use fragments in the ViewPager so I've used a PagerAdapter.

See this image:

Days of the week ViewPager

My starting point is:

and finally the layout for the ViewPager item:

Any suggestion will be appreciated.

Upvotes: 6

Views: 2556

Answers (1)

kris larson
kris larson

Reputation: 30985

So it looks like you want a carousel view.

Here's the recipe:

First, in order to show pages to the side in ViewPager, you need to provide some padding on the sides and then set clipToPadding to false:

    <android.support.v4.view.ViewPager
        android:id="@+id/weekOfTheDayPager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipToPadding="false"
        android:paddingEnd="@dimen/view_pager_padding"
        android:paddingLeft="@dimen/view_pager_padding"
        android:paddingRight="@dimen/view_pager_padding"
        android:paddingStart="@dimen/view_pager_padding"/>

Next, you need to override getPageWidth in your PagerAdapter to tell the ViewPager that you want to display three pages at a time:

    @Override
    public float getPageWidth(int position) {
        return 1F / 3F;
    }

Then you need to tell the ViewPager to use a custom PageTransformer:

    viewPager.setPageTransformer(false, new MyPageTransformer());

...

public static class MyPageTransformer implements ViewPager.PageTransformer {

    private ArgbEvaluator mColorFade = new ArgbEvaluator();

    @Override
    public void transformPage(View page, float position) {

         // position is 0 when page is centered (current)
         // -1 when page is all the way to the left 
         // +1 when page is all the way to right

         // Here's an example of how you might morph the color
         int color = mColorFade(Math.abs(position), Color.RED, Color.GRAY);
         TextView tv = (TextView) page.findViewById(R.id.dayOfTheWeekTextView);
         tv.setTextColor(color);
    }
}

There's probably something I forgot, but search SO for "android viewpager carousel" and you will find an answer in there somewhere.

Upvotes: 3

Related Questions