螢幕投影片是指整個螢幕畫面之間的轉場效果,常見於設定精靈或幻燈片等 UI。本課程將說明如何使用支援程式庫提供的 ViewPager
執行螢幕幻燈片。ViewPager
物件可自動建立畫面投影片的動畫。以下是從一個畫面內容切換到下一個畫面時的畫面幻燈片:
ViewPager
為 AndroidX 的一部分。詳情請參閱「使用 AndroidX」。
建立檢視畫面
建立稍後用於片段內容的版面配置檔案。您也需要為片段內容定義字串。以下範例包含文字檢視區塊,用於顯示文字:
<!-- 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
類別,傳回您剛才在 onCreateView()
方法中建立的版面配置。接下來,每當您需要向使用者顯示新頁面時,即可在父項活動中建立這個片段的例項:
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
會使用您先前建立的片段類別。
首先,請建立包含 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" />
建立可執行下列操作的活動:
- 將內容檢視畫面設為使用
ViewPager
的版面配置。 - 建立擴充
FragmentStatePagerAdapter
抽象類別的類別並實作getItem()
方法,提供ScreenSlidePageFragment
的例項做為新頁面。翻頁器轉接程式也要求您實作getCount()
方法,該方法會傳回轉接程式將建立的網頁數量 (在本例中為五個)。 - 將
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
介面,並提供給檢視頁面器。這個介面會公開單一方法 transformPage()
。在畫面轉換過程的每個時間點,系統會針對每個可見頁面 (通常只有一個可見頁面) 以及位於畫面外的相鄰頁面呼叫一次這個方法。
舉例來說,如果第 3 頁顯示時,使用者拖曳到第四個頁面,系統就會在手勢的每個步驟中呼叫第 2、3 和 4 頁的 transformPage()
。
在 transformPage()
的導入作業中,您可以根據畫面上頁面的實際位置 (可從 transformPage()
方法的 position
參數取得),判斷哪些頁面需要轉換,進而建立自訂的滑動動畫。
position
參數會指出指定網頁相對於畫面中央的位置。這類動態屬性會隨著使用者捲動網頁而改變。網頁填滿螢幕時,其位置值為 0
。如果頁面偏離畫面右側,則頁面的位置值為 1
。如果使用者從第 1 頁和第 2 頁之間捲動網頁,第 1 頁的排名為 -0.5,而第 2 頁的排名為 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); } } }