• Android:单Activity多Fragment,Navigation实现Fragment跳转,Fragment之间通过ViewModel共享数据


    单Activity多Fragment,Navigation实现Fragment跳转,Fragment之间通过ViewModel共享数据

    1、MainActivity

    1、activity_main.xml

    <?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"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/fragmentContainerView"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:navGraph="@navigation/nav_graph" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    2、MainActivity

    /**
     * kotlin_jetpack_navigation
     * 使用navigation  + dataBinding + viewModel
     * 三个fragment共享一个viewModel中的数据,在NavigationView中显示
     */
    class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2、HomeFragment, DetailFragment

    • FragmentA:包括SeekBar和一个按钮,点击button跳转到FragmentB
    • FragmentB:SeekBar加一和减一操作的按钮,一个返回FragmentA的按钮,即经过加减操作以后,在FragmentA上显示加减的结果。

    在这里插入图片描述
    nav_graph.xml

    
    
        
            
        
        
            
        
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    2.1、HomeFragment

    在这里插入图片描述1、fragment_home.xml

    
    
    
        
            
        
    
        
    
    
            
    
            
    
            

    2、HomeFragment

    class HomeFragment : Fragment() {
    
    
        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            // Inflate the layout for this fragment
    //        val myViewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
            val myViewModel by activityViewModels<MyViewModel>()
            val binding = DataBindingUtil.inflate<FragmentHomeBinding>(
                inflater, R.layout.fragment_home, container, false
            )
            binding.also {
                it.data = myViewModel
                it.lifecycleOwner = activity
                it.button.setOnClickListener { v ->
                    val controller = Navigation.findNavController(v)
                    controller.navigate(R.id.action_homeFragment_to_detailFragment)
                }
                myViewModel.get().value?.also { numberValue ->
                    it.seekBar.progress = numberValue
                }
                it.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
                    override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
                       myViewModel.set(p1)
                    }
    
                    override fun onStartTrackingTouch(p0: SeekBar?) {
                    }
    
                    override fun onStopTrackingTouch(p0: SeekBar?) {
                    }
    
                })
            }
    
            return binding.root
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    2.2、DetailFragment

    在这里插入图片描述1、fragment_detail.xml

    <?xml version="1.0" encoding="utf-8"?>
    <layout 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">
    
        <data>
            <variable
                name="data"
                type="cn.hk.navigation3.MyViewModel" />
        </data>
    
        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".DetailFragment">
    
    
            <androidx.constraintlayout.widget.Guideline
                android:id="@+id/guideline"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                app:layout_constraintGuide_begin="320dp"
                app:layout_constraintGuide_percent="0.5" />
    
            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@{String.valueOf(data.number)}"
                android:textSize="20sp"
                app:layout_constraintBottom_toTopOf="@+id/guideline"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
    
            <Button
                android:id="@+id/add"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="add"
                android:onClick="@{()->data.count(1)}"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toStartOf="@+id/jian"
                app:layout_constraintHorizontal_bias="0.5"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="@+id/guideline" />
    
            <Button
                android:id="@+id/jian"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="cut"
                android:onClick="@{()->data.count(-1)}"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.5"
                app:layout_constraintStart_toEndOf="@+id/add"
                app:layout_constraintTop_toTopOf="@+id/guideline" />
    
            <Button
                android:id="@+id/button3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="返回"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/add" />
        </androidx.constraintlayout.widget.ConstraintLayout>
    </layout>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71

    2、DetailFragment

    class DetailFragment : Fragment() {
    
    
        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            // Inflate the layout for this fragment
    //      val myViewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
            val myViewModel by activityViewModels<MyViewModel>()
            val binding = DataBindingUtil.inflate<FragmentDetailBinding>(
                inflater,
                R.layout.fragment_detail,
                container,
                false
            )
            binding.also {
                it.data = myViewModel
                it.lifecycleOwner = activity
                it.button3.setOnClickListener { v ->
                    val controller = Navigation.findNavController(v)
                    controller.navigate(R.id.action_detailFragment_to_homeFragment)
                }
            }
            return binding.root
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    3、MyViewModel

    class MyViewModel : ViewModel() {
        var number: MutableLiveData<Int> = MutableLiveData(0)
    
        fun get() = number
    
        fun set(result: Int) {
            number.value = result
        }
    
    
        fun count(x: Int) {
            number.value = number.value?.plus(x)
            if (number.value!! < 0)
                number.value = 0
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    参考

  • 相关阅读:
    腾讯面试——自然语言处理
    青少年近视问题不容小觑,蔡司用专业技术助力孩子视力健康发展
    (1) Java后端从0硬撸vite3+vue3+ts项目 | 起步
    两个不起眼的站内小细节,决定你的独立站转化率
    【Verilog 教程】5.2Verilog 模块例化
    (附源码)计算机毕业设计SSM基于大数据的汽车流量监控
    低代码信创开发核心技术(三):MDA模型驱动架构及元数据系统设计
    【从零开始学习 SystemVerilog】1.2、SystemVerilog TestBench (SVTB)概述
    财政政策与货币政策(下)
    PIE-engine 教程 ——利用NDWI加载青海湖三年水域影像和面积计算
  • 原文地址:https://blog.csdn.net/JMW1407/article/details/127973691