前言
最近接触到竖向整页滑动的需求,发现了viewpager2,虽然可以用如下方式
val pagerSnapHelper = PagerSnapHelper()
pagerSnapHelper.attachToRecyclerView(recycler_view)
也可以实现,官方给的viewpager2也是封装了recyclerview,用法也类似recyclerview,但是viewpager2支持fragment,保留了viewpager的特性, 就学一下比较比较。
用法
<androidx.viewpager2.widget.ViewPager2
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
/>
对于fragment
public class PagerDemoFragmentStateAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) {
private val fragments = SparseArray<Fragment>()
fun initData() {
fragments.put(0, LiveFragment())
notifyDataSetChanged()
}
override fun getItemCount(): Int = fragments.size()
override fun createFragment(position: Int): Fragment {
return fragments.get(position)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pager_demo_list)
viewpager.orientation = ViewPager2.ORIENTATION_VERTICAL
val adapter = PagerDemoFragmentStateAdapter(this).apply {
initData()
}
viewpager.adapter = adapter
viewpager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(position: Int) {
}
override fun onPageScrollStateChanged(state: Int) {
}
})
}
fun changeViewPagerScrollState(boolean canScroll){
// 是否禁止用户滑动页面
viewpager.isUserInputEnabled = canScroll
}
类似recyclerview的用法,adapter和recyclerview完全一样
class PagerDemoListAdapter(val activity: Activity) : RecyclerView.Adapter<PagerDemoListAdapter.Companion.DemoListItemViewHolder>() {
private var list: MutableList<RoomModelListItem> = mutableListOf()
fun initData(item: RoomModelListItem) {
this.list.add(item)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DemoListItemViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.pager_demo_item, parent, false)
return DemoListItemViewHolder(view, activity)
}
override fun onBindViewHolder(holder: DemoListItemViewHolder, position: Int) {
holder.bindData(list[position])
}
override fun getItemCount() = list.size
fun changeState(position: Int, state: RoomModelState) {
list[position].roomModelState = state
}
companion object {
class DemoListItemViewHolder(itemView: View, val activity: Activity) : RecyclerView.ViewHolder(itemView) {
val txt: TextView = itemView.findViewById(R.id.textView)
fun bindData(item: RoomModelListItem) {
}
}
}
}
viewpager.orientation = ViewPager2.ORIENTATION_VERTICAL
val adapter = PagerDemoListAdapter(this, this).apply {
initData(RoomModelListItem(RoomManager.getInstance().getmRoomModel(), RoomModelState.SHOWING))
}
viewpager.adapter = adapter
后记
- item的布局必须是match_parent
- viewpager2无法根据position获得当前的viewholder
网友评论