AndroidJetpack Fragment之Navigation和ViewPager2
阅读原文时间:2023年07月08日阅读:2

新的Fragment导航方式:Navigation

1.创建若干个fragment

2.添加导航

1)新建Navigation:右键res文件夹,New->Android Resource File,Resource Type选择Navigation

2)添加Freagment:Navagation文件中,点击左上角添加,按顺序添加Fragment,拖动四边的节点可以设置导航顺序

3)添加HostFragment到container中

3.添加容器

activity中拖动添加containers->NavHostFragment并选择Navagation,或者添加代码:

<fragment
        android:id="@+id/fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:navGraph="@navigation/main_nav_controler" />

4.设置跳转

​ 指定位置添加代码:

Navigation.findNavController(btn).navigate(R.id.action_mainFragment_to_detailFragment)
//navigate的参数为跳转方向,可自动补全

5.设置左上角点击返回

```

private lateinit var mNavController : NavController
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    mNavController = Navigation.findNavController(this, R.id.fragment)
    NavigationUI.setupActionBarWithNavController(this, mNavController)
}

override fun onSupportNavigateUp(): Boolean {
    return mNavController.navigateUp()
}

6.生命周期:

切换时销毁上一个Fragment,执行到onDestroy()

7.数据传递

1)bundle方式:Navigation.findController(View).navigate(resId, Bundle)

2)ViewModel方式:和Activity中使用ViewModel类似:在Fragment的onCreateView()中使用 。区别在于:使用DataBinding.inflate()绑定View;onCreateView()返回bind.getRoot()

新的页面切换控件:ViewPager2

1.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".PagerFragment">
    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewpager2"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout>

2.Adapter:

class PagerPhotoListAdapter : ListAdapter<PhotoItem, PagerPhotoViewHolder>(DIFF_UTIL) {

    object DIFF_UTIL : DiffUtil.ItemCallback<PhotoItem>() {
        override fun areItemsTheSame(oldItem: PhotoItem, newItem: PhotoItem) =
            oldItem === newItem

        override fun areContentsTheSame(oldItem: PhotoItem, newItem: PhotoItem) =
            oldItem.photoId == newItem.photoId
    }

    override fun onCreateViewHolder(parent:ViewGroup, viewType:Int):PagerPhotoViewHolder{
        val view = LayoutInflater.from(parent.context)
                                .inflate(R.layout.pager_photo_view, parent, false)
        return PagerPhotoViewHolder(view)
    }

    override fun onBindViewHolder(holder: PagerPhotoViewHolder, position: Int) {
        Glide.with(holder.itemView)
            .load(getItem(position).previewUrl)
            .placeholder(R.drawable.ic_photo_gray_24dp)
            .into(holder.itemView.pagerPhoto)
    }
}

class PagerPhotoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

3.Activity中使用:

val photoList = arguments?.getParcelableArrayList<PhotoItem>("PHOTO_LIST")        //获取数据
PagerPhotoListAdapter().apply {
    viewpager2.adapter = this        //装配适配器
    submitList(photoList)            //装配数据
}

viewpager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
    override fun onPageSelected(position: Int) {
        super.onPageSelected(position)
        photoTag.text = "${position + 1} / ${photoList?.size}"
    }
})        //注册分页变化事件
viewpager2.setCurrentItem(arguments?.getInt("PHOTO_POSITION")?:0, false)

1.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Monday" />
        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Tuesday" />
        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Wednesday" />
    </com.google.android.material.tabs.TabLayout>

    <View
        android:id="@+id/divider"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="?android:attr/listDivider" />

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

2.Adapter:

class TabViewPagerAdapter : FragmentStateAdapter(this) {
    override fun getItemCount() = 3
    override fun createFragment(position: Int) = when(position) {
        0 -> ScaleFragment()
        1 -> RotateFragment()
        else -> TranslateFragment()
    }
}