美文网首页
AndroidX:Google官方推出新的Widget:View

AndroidX:Google官方推出新的Widget:View

作者: 有没有口罩给我一个 | 来源:发表于2019-02-24 19:29 被阅读0次

今天浏览开发者官网时,发现官方发布新的控件 ViewPager2,是不是替代ViewPager?

  • 新功能
    与其前身ViewPager相比:
    1、支持RTL布局;
    2、支持竖直方向的滚动;
    3、完美解决 notifyDataSetChanged (已修复VP1的bug)

  • API 的变动
    1、FragmentStateAdapter 替换了原来的 FragmentStatePagerAdapter;
    2、RecyclerView.Adapter 替换了原来的 PagerAdapter
    3、registerOnPageChangeCallback 替换了原来的 addPageChangeListener

  • 分析
    ViewPager2也是直接继承了ViewGroup,所以并不只是扩展ViewPager,它俩实现方式不一样;

ViewPager2 的内部实现是:

private RecyclerView mRecyclerView;
private LinearLayoutManager mLayoutManager;
new PagerSnapHelper().attachToRecyclerView(mRecyclerView)

很明显:内部核心是:RecyclerView 、LinearLayoutManager和PagerSnapHelper(),

其中PagerSnapHelper的作用是限制ViewPager2一次只能滚动一页,这样就和Viewpager一样的交互方式了;

  • 使用:
    引入ViewPager2,注意这是androidx中的类,所以androidx相关的配置这里并不会介绍:

    implementation "androidx.viewpager2:viewpager2:1.0.0-alpha01"
    

和往常一样,不过需要通过android:orientation="vertical"指定滚动方向

<androidx.viewpager2.widget.ViewPager2
    android:id="@+id/vp"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />


    ViewPager2 mVp = findViewById(R.id.vp);
    MyFragmentStateAdapter adapter = new MyFragmentStateAdapter(vpData, getSupportFragmentManager());
    mVp.setAdapter(adapter);

当然Adapter还有RecyclerView.Adapter也是OK的。

相关文章

网友评论

      本文标题:AndroidX:Google官方推出新的Widget:View

      本文链接:https://www.haomeiwen.com/subject/oxmbyqtx.html