Android ViewPager2 setPageMargin unresolved

百般思念 提交于 2020-06-24 07:43:33

问题


I want to implement Carousel using View Pager2 with preview of left and right page like this:

Initially I was using view pager1 which supported. Now I think it's removed

    viewPagerhost.setPageMargin(20);

Any idea how we can achieve this using View Pager 2


回答1:


Now we need to use setPageTransformer() in Version 1.0.0-alpha05

New features

  • ItemDecorator introduced with a behaviour consistent with RecyclerView.
  • MarginPageTransformer introduced to provide an ability to create space between pages (outside of page inset).
  • CompositePageTransformer introduced to provide an ability to combine multiple PageTransformers.

SAMPLE CODE

myViewPager2.setPageTransformer(new MarginPageTransformer(1500));

Check out my previous answer if you want to implement Carousel using View Pager2




回答2:


MarginPageTransformer cannot help your need.

You must use custom setPageTrarnsformer.


Step 1

Here is my Extension Method for this.

you can check detail in this article Medium article

fun ViewPager2.setShowSideItems(pageMarginPx : Int, offsetPx : Int) {

    clipToPadding = false
    clipChildren = false
    offscreenPageLimit = 3

    setPageTransformer { page, position ->

        val offset = position * -(2 * offsetPx + pageMarginPx)
        if (this.orientation == ViewPager2.ORIENTATION_HORIZONTAL) {
            if (ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL) {
                page.translationX = -offset
            } else {
                page.translationX = offset
            }
        } else {
            page.translationY = offset
        }
    }

}

Step 2

set pageMarginPx and offsetPx with your use case.

<resources>
    <dimen name="pageMargin">20dp</dimen>
    <dimen name="pagerOffset">30dp</dimen>
    <dimen name="pageMarginAndoffset">50dp</dimen>
</resources>

Step 3

set your side margin of layout item in your xml.

like this

    <androidx.cardview.widget.CardView
            app:cardCornerRadius="12dp"

            android:layout_marginTop="16dp"
            android:layout_marginBottom="16dp"

            android:layout_marginLeft="@dimen/pageMarginAndoffset"
            android:layout_marginRight="@dimen/pageMarginAndoffset"

            android:layout_width="match_parent"
            android:layout_height="match_parent">



回答3:


you can use this code

   viewPager.setPageTransformer(new MarginPageTransformer(margin as PX));

but if you want to use DP you can use the below function for convert PX to DP

 private  int pxToDp(int px) {
    return (int) (px / Resources.getSystem().getDisplayMetrics().density);
}


来源:https://stackoverflow.com/questions/56114430/android-viewpager2-setpagemargin-unresolved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!