屏幕滑动是从一个整个屏幕到另一个屏幕的过渡,在诸如以下的界面中很常见:
设置向导和幻灯片演示。本主题介绍了如何使用
ViewPager2
对象。ViewPager2
对象可自动为屏幕滑动添加动画效果。下面是一个示例
:
如果您想直接查看完整的工作示例, 查看 此示例应用。
<ph type="x-smartling-placeholder">若要使用“ViewPager2
”,您需要添加一些
AndroidX 依赖项
项目。然后按照以下部分中列出的步骤操作。
创建视图
创建稍后要用于 fragment 内容的布局文件。您还需要定义一个字符串 fragment 的内容。以下示例包含一个文本视图,其中显示了一些 文本:
<!-- fragment_screen_slide_page.xml --> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/content" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView style="?android:textAppearanceMedium" android:padding="16dp" android:lineSpacingMultiplier="1.2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/lorem_ipsum" /> </ScrollView>
创建 Fragment
创建
Fragment
类
将返回您在
onCreateView()
方法。然后,当您需要
显示给用户的新页面:
Kotlin
import androidx.fragment.app.Fragment class ScreenSlidePageFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View = inflater.inflate(R.layout.fragment_screen_slide_page, container, false) }
Java
import androidx.fragment.app.Fragment; ... public class ScreenSlidePageFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return (ViewGroup) inflater.inflate( R.layout.fragment_screen_slide_page, container, false); } }
添加 ViewPager2
ViewPager2
对象内置滑动手势,可在页面之间转换;以及
默认情况下,它们会显示屏幕滑动动画,因此您无需创建自己的动画。
ViewPager2
人使用
FragmentStateAdapter
对象作为要显示的新页面的提供,因此 FragmentStateAdapter
使用
Fragment 类。
首先,创建一个包含 ViewPager2
对象的布局:
<!-- activity_screen_slide.xml --> <androidx.viewpager2.widget.ViewPager2 xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent" />
创建一个执行以下操作的 activity:
- 将内容视图设置为包含
ViewPager2
的布局。 - 创建一个扩展
FragmentStateAdapter
抽象类的类,并且 实现了createFragment()
方法提供ScreenSlidePageFragment
实例作为新页面。您必须 实施getItemCount()
方法,该方法会返回适配器创建的页面数。还有 示例中的五个。 - 将
FragmentStateAdapter
与ViewPager2
对象挂钩。
Kotlin
import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity ... /** * The number of pages (wizard steps) to show in this demo. */ private const val NUM_PAGES = 5 class ScreenSlidePagerActivity : FragmentActivity() { /** * The pager widget, which handles animation and allows swiping horizontally * to access previous and next wizard steps. */ private lateinit var viewPager: ViewPager2 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_screen_slide) // Instantiate a ViewPager2 and a PagerAdapter. viewPager = findViewById(R.id.pager) // The pager adapter, which provides the pages to the view pager widget. val pagerAdapter = ScreenSlidePagerAdapter(this) viewPager.adapter = pagerAdapter } override fun onBackPressed() { if (viewPager.currentItem == 0) { // If the user is currently looking at the first step, allow the system to handle // the Back button. This calls finish() on this activity and pops the back stack. super.onBackPressed() } else { // Otherwise, select the previous step. viewPager.currentItem = viewPager.currentItem - 1 } } /** * A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in * sequence. */ private inner class ScreenSlidePagerAdapter(fa: FragmentActivity) : FragmentStateAdapter(fa) { override fun getItemCount(): Int = NUM_PAGES override fun createFragment(position: Int): Fragment = ScreenSlidePageFragment() } }
Java
import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; ... public class ScreenSlidePagerActivity extends FragmentActivity { /** * The number of pages (wizard steps) to show in this demo. */ private static final int NUM_PAGES = 5; /** * The pager widget, which handles animation and allows swiping horizontally to access previous * and next wizard steps. */ private ViewPager2 viewPager; /** * The pager adapter, which provides the pages to the view pager widget. */ private FragmentStateAdapter pagerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_screen_slide); // Instantiate a ViewPager2 and a PagerAdapter. viewPager = findViewById(R.id.pager); pagerAdapter = new ScreenSlidePagerAdapter(this); viewPager.setAdapter(pagerAdapter); } @Override public void onBackPressed() { if (viewPager.getCurrentItem() == 0) { // If the user is currently looking at the first step, allow the system to handle the // Back button. This calls finish() on this activity and pops the back stack. super.onBackPressed(); } else { // Otherwise, select the previous step. viewPager.setCurrentItem(viewPager.getCurrentItem() - 1); } } /** * A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in * sequence. */ private class ScreenSlidePagerAdapter extends FragmentStateAdapter { public ScreenSlidePagerAdapter(FragmentActivity fa) { super(fa); } @Override public Fragment createFragment(int position) { return new ScreenSlidePageFragment(); } @Override public int getItemCount() { return NUM_PAGES; } } }
使用 PageTransformer 自定义动画
要显示与默认屏幕滑动动画不同的动画,请实现
ViewPager2.PageTransformer
接口并将其提供给 ViewPager2
对象。该接口公开了一个
方法,
transformPage()
。
在屏幕过渡的每个点,都会针对每个可见页面调用此方法一次,
通常只有一个可见页面,并且对于屏幕之外的相邻页面而言,例如,如果第三页是
当用户拖向第 4 页时,第 2 页会调用 transformPage()
,
然后,在您的 transformPage()
实现中,您可以创建自定义幻灯片
从而根据页面在页面上的位置确定
屏幕上。通过position
transformPage()
方法。
position
参数指示指定网页相对于
屏幕中央此参数是一个动态属性,会随着用户滚动浏览而发生变化
一系列页面。当页面填满屏幕时,其位置值为 0
。如果某个页面
绘制在屏幕右侧外,其位置值为 1
。如果用户滚动屏幕
位于第 1 页和第 2 页中间,第一页的位置为 -0.5
,第二页的位置为
0.5
的位置。根据页面在屏幕上的位置,您可以创建
通过使用
setAlpha()
,
setTranslationX()
,
或
setScaleY()
。
如果您在实施了
PageTransformer
,
致电
setPageTransformer()
与您的实现一起应用自定义动画。例如,如果您有一个
名为“ZoomOutPageTransformer
”的PageTransformer
,您可以设置自己的自定义
例如:
Kotlin
val viewPager: ViewPager2 = findViewById(R.id.pager) ... viewPager.setPageTransformer(ZoomOutPageTransformer())
Java
ViewPager2 viewPager = findViewById(R.id.pager); ... viewPager.setPageTransformer(new ZoomOutPageTransformer());
请参阅缩小页面转换器和
深度页面转换器部分,获取
PageTransformer
。
缩小页面转换器
在相邻页面之间滚动时,此页面转换器会缩小和淡化页面。以信息页形式 当距离中心较近时,它会恢复正常大小并淡入。
Kotlin
private const val MIN_SCALE = 0.85f private const val MIN_ALPHA = 0.5f class ZoomOutPageTransformer : ViewPager2.PageTransformer { override fun transformPage(view: View, position: Float) { view.apply { val pageWidth = width val pageHeight = height when { position < -1 -> { // [-Infinity,-1) // This page is way off-screen to the left. alpha = 0f } position <= 1 -> { // [-1,1] // Modify the default slide transition to shrink the page as well. val scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position)) val vertMargin = pageHeight * (1 - scaleFactor) / 2 val horzMargin = pageWidth * (1 - scaleFactor) / 2 translationX = if (position < 0) { horzMargin - vertMargin / 2 } else { horzMargin + vertMargin / 2 } // Scale the page down (between MIN_SCALE and 1). scaleX = scaleFactor scaleY = scaleFactor // Fade the page relative to its size. alpha = (MIN_ALPHA + (((scaleFactor - MIN_SCALE) / (1 - MIN_SCALE)) * (1 - MIN_ALPHA))) } else -> { // (1,+Infinity] // This page is way off-screen to the right. alpha = 0f } } } } }
Java
public class ZoomOutPageTransformer implements ViewPager2.PageTransformer { private static final float MIN_SCALE = 0.85f; private static final float MIN_ALPHA = 0.5f; public void transformPage(View view, float position) { int pageWidth = view.getWidth(); int pageHeight = view.getHeight(); if (position < -1) { // [-Infinity,-1) // This page is way off-screen to the left. view.setAlpha(0f); } else if (position <= 1) { // [-1,1] // Modify the default slide transition to shrink the page as well. float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position)); float vertMargin = pageHeight * (1 - scaleFactor) / 2; float horzMargin = pageWidth * (1 - scaleFactor) / 2; if (position < 0) { view.setTranslationX(horzMargin - vertMargin / 2); } else { view.setTranslationX(-horzMargin + vertMargin / 2); } // Scale the page down (between MIN_SCALE and 1). view.setScaleX(scaleFactor); view.setScaleY(scaleFactor); // Fade the page relative to its size. view.setAlpha(MIN_ALPHA + (scaleFactor - MIN_SCALE) / (1 - MIN_SCALE) * (1 - MIN_ALPHA)); } else { // (1,+Infinity] // This page is way off-screen to the right. view.setAlpha(0f); } } }
深度页面转换器
此页面转换器使用默认滑动动画将页面向左滑动,同时使用 “深度”右滑页面的动画。此深度动画会使页面淡出并 以线性方式缩容。
在深度动画期间,默认动画(屏幕滑动)仍会进行,因此您必须 以 X 为负向抵消屏幕滑动。例如:
Kotlin
view.translationX = -1 * view.width * position
Java
view.setTranslationX(-1 * view.getWidth() * position);
以下示例展示了如何抵消运行中的默认屏幕滑动动画 页面转换器:
Kotlin
private const val MIN_SCALE = 0.75f @RequiresApi(21) class DepthPageTransformer : ViewPager2.PageTransformer { override fun transformPage(view: View, position: Float) { view.apply { val pageWidth = width when { position < -1 -> { // [-Infinity,-1) // This page is way off-screen to the left. alpha = 0f } position <= 0 -> { // [-1,0] // Use the default slide transition when moving to the left page. alpha = 1f translationX = 0f translationZ = 0f scaleX = 1f scaleY = 1f } position <= 1 -> { // (0,1] // Fade the page out. alpha = 1 - position // Counteract the default slide transition. translationX = pageWidth * -position // Move it behind the left page. translationZ = -1f // Scale the page down (between MIN_SCALE and 1). val scaleFactor = (MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position))) scaleX = scaleFactor scaleY = scaleFactor } else -> { // (1,+Infinity] // This page is way off-screen to the right. alpha = 0f } } } } }
Java
@RequiresApi(21) public class DepthPageTransformer implements ViewPager2.PageTransformer { private static final float MIN_SCALE = 0.75f; public void transformPage(View view, float position) { int pageWidth = view.getWidth(); if (position < -1) { // [-Infinity,-1) // This page is way off-screen to the left. view.setAlpha(0f); } else if (position <= 0) { // [-1,0] // Use the default slide transition when moving to the left page. view.setAlpha(1f); view.setTranslationX(0f); view.setTranslationZ(0f); view.setScaleX(1f); view.setScaleY(1f); } else if (position <= 1) { // (0,1] // Fade the page out. view.setAlpha(1 - position); // Counteract the default slide transition. view.setTranslationX(pageWidth * -position); // Move it behind the left page view.setTranslationZ(-1f); // Scale the page down (between MIN_SCALE and 1). float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position)); view.setScaleX(scaleFactor); view.setScaleY(scaleFactor); } else { // (1,+Infinity] // This page is way off-screen to the right. view.setAlpha(0f); } } }
其他资源
如需详细了解 ViewPager2
,请参阅下面列出的其他资源。
示例
- ViewPager2 示例,位于 GitHub。
视频
- 新篇章: 迁移到 ViewPager2(2019 年 Android 开发者峰会)