使用ViewModel在Fragment之间共享数据

  • 需要依赖Fragment的扩展函数库 implementation "androidx.fragment:fragment-ktx:1.2.5"

  • 我们建立一个需要传值的Viemodel类,这里只是简单传递个boolean值

package com.example.jitpackdemo.ui.main

import android.content.ClipData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

class SharedViewModel : ViewModel() {
    val selected = MutableLiveData<Boolean>()
}
  • 在Mactivity中关联此ViewModel
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_activity)
        var shareModel = ViewModelProviders.of(this).get(SharedViewModel::class.java)
        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                .replace(R.id.container, MainFragment.newInstance())
                .commitNow()
        }
        shareModel.selected.value= true
    }
}

可以看到这里我们区改变了数值为true

  • Fragment中我们只需要private val model: SharedViewModel by activityViewModels1() 引入刚才我们创建的viewModel
class MainFragment : Fragment() {

    companion object {
        fun newInstance() = MainFragment()
    }

    private lateinit var viewModel: MainViewModel
    private val model: SharedViewModel by activityViewModels1()
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.main_fragment, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
        model.selected.observe(viewLifecycleOwner, Observer {
            Toast.makeText(activity,it.toString(),Toast.LENGTH_SHORT).show()
        })
    }

}

这样我们就可以在Fragment中正常收到我们从Activity的数值了

推荐阅读更多精彩内容