屏幕滑动是两个完整屏幕之间的切换,在设置向导或幻灯片等界面中很常见。本节课向您介绍如何使用支持库提供的 ViewPager
创建屏幕滑动。ViewPager
对象可自动为屏幕滑动添加动画。下面是一个屏幕滑动的效果,是从一个屏幕的内容切换到下一个屏幕的内容:
ViewPager
是 AndroidX 的一部分。如需了解详情,请参阅使用 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()
方法中创建的布局。然后,每当您需要向用户显示新页面时,便可以在父 activity 中创建此 fragment 的实例:
Kotlin
import android.support.v4.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 android.support.v4.app.Fragment; ... public class ScreenSlidePageFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate( R.layout.fragment_screen_slide_page, container, false); return rootView; } }
添加 ViewPager
ViewPager
对象内置滑动手势可在页面间转换,并且默认显示屏幕滑动动画,因此您无需创建自己的动画。ViewPager
使用 PagerAdapter
对象提供要显示的新页面,因此 PagerAdapter
将使用您之前创建的 fragment 类。
首先,创建一个包含 ViewPager
的布局:
<!-- activity_screen_slide.xml --> <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent" />
创建一个可执行以下操作的 activity:
- 将内容视图设置为包含
ViewPager
的布局。 - 创建一个扩展
FragmentStatePagerAdapter
抽象类的类,并实现getItem()
方法,以提供ScreenSlidePageFragment
的实例作为新页面。分页器适配器还要求您实现getCount()
方法,该方法会返回适配器将创建的页数(本例中为 5 个)。 - 将
PagerAdapter
与ViewPager
挂钩。
Kotlin
import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager ... /** * 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 mPager: ViewPager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_screen_slide) // Instantiate a ViewPager and a PagerAdapter. mPager = findViewById(R.id.pager) // The pager adapter, which provides the pages to the view pager widget. val pagerAdapter = ScreenSlidePagerAdapter(supportFragmentManager) mPager.adapter = pagerAdapter } override fun onBackPressed() { if (mPager.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. mPager.currentItem = mPager.currentItem - 1 } } /** * A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in * sequence. */ private inner class ScreenSlidePagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) { override fun getCount(): Int = NUM_PAGES override fun getItem(position: Int): Fragment = ScreenSlidePageFragment() } }
Java
import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; ... 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 ViewPager mPager; /** * The pager adapter, which provides the pages to the view pager widget. */ private PagerAdapter pagerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_screen_slide); // Instantiate a ViewPager and a PagerAdapter. mPager = (ViewPager) findViewById(R.id.pager); pagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager()); mPager.setAdapter(pagerAdapter); } @Override public void onBackPressed() { if (mPager.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. mPager.setCurrentItem(mPager.getCurrentItem() - 1); } } /** * A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in * sequence. */ private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter { public ScreenSlidePagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { return new ScreenSlidePageFragment(); } @Override public int getCount() { return NUM_PAGES; } } }
使用 PageTransformer 自定义动画
要显示与默认屏幕滑动动画不同的动画,请实现 ViewPager.PageTransformer
接口并将其提供给 Viewpager。该接口只会公开一个方法 transformPage()
。在屏幕切换的每个点,系统会针对每个可见页面(通常只有一个可见页面)和刚刚离开屏幕的相邻页面调用此方法。
例如,如果第 3 页可见且用户拖向第 4 页,则在手势的每个步骤,都会为第 2 页、第 3 页和第 4 页调用 transformPage()
。
然后在 transformPage()
实现中,您可以创建自定义滑动动画,方法是从 transformPage()
方法的 position
参数获取页面在屏幕上的位置,然后根据该位置确定需要转换哪些页面。
position
参数指示给定页面相对于屏幕中心的位置。它是一个动态属性,会随着用户滚动浏览页面而变化。当页面填满整个屏幕时,其位置值为 0
。
当页面刚刚离开屏幕右侧时,其位置值为 1
。如果用户在第一页和第二页之间滚动到一半,则第一页的位置为 -0.5,第二页的位置为 0.5。根据页面在屏幕上的位置,您可以使用 setAlpha()
、setTranslationX()
或 setScaleY()
等方法来设置页面属性,从而创建自定义幻灯片动画。
如果您具有 PageTransformer
实现,请通过您的实现调用 setPageTransformer()
来应用自定义动画。例如,如果您有一个名为 ZoomOutPageTransformer
的 PageTransformer
,则可以按如下所示设置自定义动画:
Kotlin
val mPager: ViewPager = findViewById(R.id.pager) ... mPager.setPageTransformer(true, ZoomOutPageTransformer())
Java
ViewPager mPager = (ViewPager) findViewById(R.id.pager); ... mPager.setPageTransformer(true, new ZoomOutPageTransformer());
如需查看 PageTransformer
的示例和视频,请参阅缩小页面转换器和深度页面转换器部分。
缩小页面转换器
在相邻页面之间滚动时,此页面转换器会缩小和淡化页面。随着页面越来越靠近中心,页面会恢复到正常大小并淡入。
Kotlin
private const val MIN_SCALE = 0.85f private const val MIN_ALPHA = 0.5f class ZoomOutPageTransformer : ViewPager.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 ViewPager.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 class DepthPageTransformer : ViewPager.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 scaleX = 1f scaleY = 1f } position <= 1 -> { // (0,1] // Fade the page out. alpha = 1 - position // Counteract the default slide transition translationX = pageWidth * -position // 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
public class DepthPageTransformer implements ViewPager.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.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); // 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); } } }