1.ViewPager2和父布局添加 android:clipChildren=”false” 属性
2.ViewPager2左右两侧增加Margin
3.ViewPager2的OffscreenPageLimit设置为大于等于1的值
binding.viewPager.setOffscreenPageLimit(1);
4.ViewPager2设置PageTransformer
binding.viewPager.setPageTransformer(new GalleryTransformer());
import android.view.View; import androidx.viewpager2.widget.ViewPager2; public class GalleryTransformer implements ViewPager2.PageTransformer { public static float MIN_ALPHA = 0.8f; public static float MIN_SCALE = 0.8f; @Override public void transformPage(View page, float position) { if (position < -1 || position > 1) { page.setAlpha(MIN_ALPHA); page.setScaleX(MIN_SCALE); page.setScaleY(MIN_SCALE); } else if (position <= 1) { // [-1,1] float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position)); float scaleX; if (position < 0) { scaleX = 1 + 0.1f * position; } else { scaleX = 1 - 0.1f * position; } page.setScaleX(scaleX); page.setScaleY(scaleX); page.setAlpha(MIN_ALPHA + (scaleFactor - MIN_SCALE) / (1 - MIN_SCALE) * (1 - MIN_ALPHA)); } } }
参考资料: