美文网首页Kevin Learn Android
Kevin Learn Kotlin:Fragment 必知必会

Kevin Learn Kotlin:Fragment 必知必会

作者: Kevin_小飞象 | 来源:发表于2021-12-23 14:32 被阅读0次
    17.jpg

    生命周期

    onAttach() → onCreate() → onCreateView() →onActivityCreated() → onStart() → onResume() → onPause() → onStop() → onDestroyView() → onDestroy() → onDetach()


    fragment.png
    • onAttach()
      当该 Fragment 被添加到 Activity 中会回调,只会被调用一次;

    • onCreate()
      创建 Fragment 时回调,只会被调用一次;

    • onCreateView()
      每次创建,绘制该 Fragment 的 View 组件时回调,会将显示的 View 返回;

    • onActivityCreated()
      当 Fragment 所在的 Activity 启动完成后回调;

    • onStart()
      启动 Fragment 时被回调

    • onResume()
      恢复 Fragment 时被回调,onStart() 方法后一定回调 onResume() 方法 onStart() 可见,onResume()后才能交互;

    • onPause()
      暂停 Fragment 时被回调

    • onStop()
      停止 Fragment 时被回调

    • onDestroyView()
      销毁该 Fragment 所包含的 View 组件时使用

    • onDestroy()
      销毁 Fragment 时被毁掉

    • onDetach()
      将该Fragment 从 Activity 被删除/替换完成后回调该方法;onDestroy() 方法后一定会回调该方法;该方法只调用一次

    Fragment 的动态添加与数据传递

    动态添加 Fragment

    // 1、定义 StudyFragment 需要继承自 Fragment, 并且绑定布局文件
    class StudyFragment : Fragment(R.layout.fragment_study) {}
    
    // 2、在Activity 中使用
    class StudyActivity: AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_study)
    
            val fragment = StudyFragment()
            val ft = supportFragmentManager.beginTransaction()
            ft.replace(R.id.container,fragment)
            ft.commitAllowingStateLoss()
        }
    }
    

    Activity 向 Fragment 中传递数据

    class StudyActivity: AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_study)
    
            val fragment = StudyFragment()
            val bundle = Bundle()
            bundle.putString("name","Kevin")
            bundle.putInt("age",20)
            fragment.arguments = bundle
    
            val ft = supportFragmentManager.beginTransaction()
            ft.replace(R.id.container,fragment)
            ft.commitAllowingStateLoss()
        }
    }
    
    ---------------------------------------分割线---------------------------------------
    class StudyFragment : Fragment(R.layout.fragment_study) {
        private val TAG = "StudyFragment"
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            val name = arguments?.getString("name")
            val age = arguments?.getInt("age")
    
            tab_study.text = name
            tab_stable.text = "$age"
        }
    }
    

    实例

    image.png

    需求:实现底部导航栏

    1. Activity 页面布局
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/nav_view"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="0dp"
            android:layout_marginEnd="0dp"
            android:background="?android:attr/windowBackground"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:menu="@menu/bottom_nav_menu" />
    
        <fragment
            android:id="@+id/nav_host_fragment_activity_main"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toTopOf="@id/nav_view"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:navGraph="@navigation/mobile_navigation" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
    1. menu/bottom_nav_menu.xml
    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item
            android:id="@+id/navigation_home"
            android:icon="@drawable/ic_home_black_24dp"
            android:title="@string/title_home" />
    
        <item
            android:id="@+id/navigation_study"
            android:icon="@mipmap/icon_menu_study"
            android:title="@string/title_study" />
    
        <item
            android:id="@+id/navigation_dashboard"
            android:icon="@drawable/ic_dashboard_black_24dp"
            android:title="@string/title_dashboard" />
    
        <item
            android:id="@+id/navigation_notifications"
            android:icon="@drawable/ic_notifications_black_24dp"
            android:title="@string/title_notifications" />
    
    </menu>
    
    1. navigation/mobile_navigation
    <?xml version="1.0" encoding="utf-8"?>
    <navigation 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:id="@+id/mobile_navigation"
        app:startDestination="@+id/navigation_home">
    
        <fragment
            android:id="@+id/navigation_home"
            android:name="com.hkt.firstapp.ui.home.HomeFragment"
            android:label="@string/title_home"
            tools:layout="@layout/fragment_home" />
    
        <fragment
            android:id="@+id/navigation_study"
            android:name="com.hkt.firstapp.ui.study.StudyFragment"
            android:label="@string/title_study"
            tools:layout="@layout/fragment_study" />
    
        <fragment
            android:id="@+id/navigation_dashboard"
            android:name="com.hkt.firstapp.ui.dashboard.DashboardFragment"
            android:label="@string/title_dashboard"
            tools:layout="@layout/fragment_dashboard" />
    
        <fragment
            android:id="@+id/navigation_notifications"
            android:name="com.hkt.firstapp.ui.notifications.NotificationsFragment"
            android:label="@string/title_notifications"
            tools:layout="@layout/fragment_notifications" />
    </navigation>
    
    1. MainActivitry.kt
    class MainActivity : AppCompatActivity() {
        private val TAG = "MainActivity"
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            setContentView(R.layout.activity_main)
            val navView: BottomNavigationView = findViewById(R.id.nav_view)
    
            val navController = findNavController(R.id.nav_host_fragment_activity_main)
    
            navView.setupWithNavController(navController)
    
        }
    }
    
    1. DashboardFragment.kt
    class DashboardFragment : Fragment(R.layout.fragment_dashboard) {
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
    
            rv_fruit.layoutManager = GridLayoutManager(context, 3)
            rv_fruit.adapter = MyAdapter()
        }
    
        inner class MyAdapter : RecyclerView.Adapter<MyViewHolder>(){
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
                val itemView = LayoutInflater.from(context)
                    .inflate(R.layout.item_fruit_grid,parent,false)
                return MyViewHolder(itemView)
            }
    
            override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
                holder.itemView.iv_fruit.setImageResource(R.mipmap.icon_jetpack)
    
                holder.itemView.tv_fruit_name.text = "【${position}】Apple"
            }
    
            override fun getItemCount(): Int {
                return 20
            }
    
        }
    
        class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {}
    }
    

    相关文章

      网友评论

        本文标题:Kevin Learn Kotlin:Fragment 必知必会

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