畫面投影片是指從一個畫面轉換到另一個畫面的轉場效果,而且 UI 這類投影片很常見,例如:
設定精靈和投影播放本主題將說明如何使用
ViewPager2
物件。ViewPager2
物件可自動為畫面投影片製作動畫。舉例來說
這個畫面投影片的作用:
如果您想直接查看完整工作範例 檢視 。
如要使用「ViewPager2
」,請先新增
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 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
會使用
您建立的片段類別。
首先,請建立包含 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" />
建立可執行下列操作的活動:
- 將內容檢視畫面設為使用
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()
。
系統會在畫面轉換的每個時間點,針對每個可見網頁呼叫一次這個方法;
通常只有一個可見網頁,且通常只會出現在畫面外的頁面。舉例來說,假設網頁 3 是
把使用者拖曳到第 4 頁後,系統呼叫了第 2 頁的 transformPage()
。
每個手勢的每個步驟
您可以在 transformPage()
實作中建立自訂投影片
動畫,接著根據網頁上
。從position
transformPage()
方法。
position
參數代表指定網頁與
位於畫面中央這個參數屬於動態屬性,會隨著使用者捲動畫面變更
顯示一組網頁網頁填滿螢幕時,網頁的排名值為 0
。網頁
會繪製在畫面右側,其位置值為 1
。如果使用者捲動畫面
第 1 頁和第 2 頁之間,第 1 頁的排名為 -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); } } }
深度頁面轉換工具
此頁面轉換器使用預設投影片動畫來向左滑頁面動畫,同時使用 「深度」動畫,將頁面向右滑動這段深度動畫會淡出頁面 資源數量
深度動畫仍會播放預設動畫 (畫面投影片),因此您必須 以負數翻譯為負數。例如:
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 開發人員高峰會)