viewPager2如今已經發布到1.0.0-beta04
,它相較於viewPager我認爲比較重大的改善就是採用RecyclerView的Adapter,這使得它能夠很方便的動態添加,移除,變動item,這在老版本的ViewPager中是比較麻煩的android
dependencies {
implementation "androidx.viewpager2:viewpager2:1.0.0-beta04"
}
複製代碼
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewPager2"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
複製代碼
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/tvTitle"
android:textColor="@android:color/white"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
tools:text= "item"
android:textSize="32sp"
android:layout_height="wrap_content" />
</RelativeLayout>
複製代碼
class ViewPagerAdapter : RecyclerView.Adapter<PagerVH>() {
private val colors = intArrayOf(
android.R.color.black,
android.R.color.holo_red_light,
android.R.color.holo_blue_dark,
android.R.color.holo_purple
)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PagerVH =
PagerVH(LayoutInflater.from(parent.context).inflate(R.layout.item_page, parent, false))
override fun getItemCount(): Int = colors.size
override fun onBindViewHolder(holder: PagerVH, position: Int) = holder.itemView.run {
tvTitle.text = "item $position"
container.setBackgroundResource(colors[position])
}
}
class PagerVH(itemView: View) : RecyclerView.ViewHolder(itemView)
複製代碼
將ViewPager2和adapter關聯git
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewPager2.adapter = ViewPagerAdapter()
}
}
複製代碼
看起來是否是很是簡單,使用方法基本和RecyclerView相同github
若是以前在viewpager中使用垂直滑動只可以用第三方庫,如今使用ViewPager2,咱們能夠很方便的切換滑動方向app
viewPager2.orientation = ViewPager2.ORIENTATION_VERTICAL
複製代碼
同樣能夠在ViewPager2中搭配fragments使用less
class PagerFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.item_page, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
arguments?.let {
container.setBackgroundResource(it.getInt("color"))
tvTitle.text = "Item ${it.getInt("position")}"
}
}
}
複製代碼
class ViewPagerFragmentStateAdapter(fm: FragmentManager) : FragmentStateAdapter(fm) {
private val colors = intArrayOf(
android.R.color.black,
android.R.color.holo_red_light,
android.R.color.holo_blue_dark,
android.R.color.holo_purple
)
override fun getItem(position: Int): Fragment = PagerFragment().apply {
arguments = bundleOf(
"color" to colors[position],
"position" to position
)
}
override fun getItemCount(): Int = colors.size
}
複製代碼
viewPager2.adapter = ViewPagerFragmentStateAdapter(supportFragmentManager)
複製代碼
若是用以前的viewPager,若是咱們要添加監聽器,是這樣的:ide
oldViewPager.addOnPageChangeListener(object:ViewPager.OnPageChangeListener{
override fun onPageScrollStateChanged(state: Int) {
// useless
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
// useless too
}
override fun onPageSelected(position: Int) {
// useful
}
})
複製代碼
不得不重寫三個方法,而ViewPager2中,使用OnPageChangeCallback能夠很方便的添加監聽器佈局
viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
// No boilerplate, only useful
}
})
複製代碼
若是想要搭配tablayout,使用一個TabLayoutMediator類就能夠了動畫
TabLayoutMediator(tabLayout, viewPager) { tab, position ->
tab.text = Card.DECK[position].toString()
}.attach()
複製代碼
直接像RecyclerView同樣動態添加,刪除就能夠了ui
adapter.notifyItemRangeInserted(position, count);
adapter.notifyItemRangeRemoved(position, count);
adapter.notifyItemMoved(fromPosition, toPosition);
adapter.notifyItemRangeChanged(position, count, payload);
複製代碼
當用戶由一個item切換到另一個item,可不能夠有一些額外的動畫呢。google
基於ViewPager2.PagerTransformer能夠實現這樣的功能。
主要是建立一個類繼承ViewPager2.PageTransformer,重寫transformPage()
這個方法,這個方法有兩個參數,一個是View, 一個position(float),具體的使用就是position參數表明了此刻用戶滑動到了哪一個位置,而後根據這個位置position去計算你想要讓View所作的變換,這些變換包括但不限於
例如
private val mAnimator = ViewPager2.PageTransformer { page, position ->
val absPos = Math.abs(position)
page.apply {
rotation = if (rotateCheckBox.isChecked) position * 360 else 0f
translationY = if (translateY) absPos * 500f else 0f
translationX = if (translateX) absPos * 350f else 0f
if (scaleCheckBox.isChecked) {
val scale = if (absPos > 1) 0F else 1 - absPos
scaleX = scale
scaleY = scale
} else {
scaleX = 1f
scaleY = 1f
}
}
}
複製代碼
以後再和viewPager綁定
viewPager.setPageTransformer(mAnimator)
複製代碼
項目:
參考文章: