ViewPager inside Fragment with margins and page tr

2019-04-06 19:51发布

问题:

I have a viewpager with fragments inside it.

I use the code similar to e.g.

ViewPager margin in PageTransformer transformations

and padding so you can see the faded out edge of fragments on either side of the fragment you are currently viewing.

But the problem is when the viewpager is first started, the fragments on either side are not faded and zoomed out.

I.e. the transformPage method of my ZoomOutPageTransformer doesn't get called until you start swiping, so the initial off-page right / left or wherever views look wrong, and then 'jump' to looking right once a swipe is done.

Any ideas how I can cause it to render correctly, so e.g. if I call

myViewPager.setCurrentItem(1) - or anything, the pages to the sides will be appropriately zoomed out.

How can I get the viewpager to render correctly oncreate with the zoomoutpagetransformer applied to the 'off screen' fragments?

回答1:

Basically the PageTransformer's transformPage() method return the wrong position when you play with padding and margin on the view pager. Seems to be a framework bug as stated here. The workaround explained there wasn't working for me.

So I came up with another solution, faking a drag on the view pager as soon as you put data on its associated adapter.

private void invalidatePageTransformer(final ViewPager pager)
{
    new Handler().post(new Runnable() {
        @Override
        public void run() {
            //no need to invalidate if we have no adapter or no items
            if (pager.getAdapter() != null && pager.getAdapter().getCount() > 0)
            {
                //import check here, only fakeDrag if "beginFakeDrag()" returns true
                if (pager.beginFakeDrag())
                {
                    pager.fakeDragBy(0f);
                    pager.endFakeDrag();
                }
            }
        }
    });

}


回答2:

I know I'm too late to answer, but I faced the same issue and did not find any answer to this. So for anyone who faces the same issue, here is something:

So basically the page transformer does not get correctly called for the next item when it loads the first time, though it works well when scrolled for the first time.

So I wrote a few lines to scroll the page a little and get it back which gets us the required view:

 viewPager.scrollBy(5,0);
 viewPager.scrollBy(-5,0);


回答3:

I've had a similar problem and solved it by adding:

// ... your ViewPager setup code here
myViewPager.setPageMargin(1);


回答4:

I've tried to adjust padding of ViewPager then i found 45dp will let item that inside ViewPager rending correctly.

<android.support.v4.view.ViewPager
        ...
        android:paddingTop="45dp"
        ...
        />