Android开发Viewpager2和SlidingTabLayout结合使用
第一步:xml
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/cl_select_edu_auth"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="@id/only_iv_sesame_desc"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginTop="@dimen/dp_30"
android:background="@color/white"
android:layout_marginLeft="@dimen/d40px"
android:layout_marginRight="@dimen/d40px">
<com.flyco.tablayout.SlidingTabLayout
android:id="@+id/stl_edu_auth"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_40"
app:tl_indicator_color="@color/c_main"
app:tl_indicator_height="@dimen/dp_4"
app:tl_indicator_width="@dimen/dp_16"
app:tl_indicator_corner_radius="@dimen/dp_2"
app:tl_tab_space_equal="true"
app:tl_textsize="16sp"
app:tl_textSelectColor="@color/black"
app:tl_textUnselectColor="@color/c_aa"
app:tl_textSelectSize="18sp"
app:tl_textBold="BOTH"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="@dimen/dp_12"/>
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/vp2_edu_auth"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="@id/stl_edu_auth"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="@dimen/dp_24"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
第二步:代码使用
vp2_edu_auth.adapter = object : FragmentStateAdapter(this){
override fun getItemCount(): Int {
return 2
}
override fun createFragment(position: Int): Fragment {
return OnlyEduAuthTypeFragment.newInstance(position )
}
}
stl_edu_auth.setViewPager2(vp2_edu_auth , arrayListOf<String>(getString(R.string.chinese_mainland),getString(
R.string.international)))