Android ViewModel

Android ViewModel

ViewModel 类旨在以注重生命周期的方式存储和管理界面的相关数据, viewModel 可以在屏幕发生旋转灯配置更改之后继续留存 .

android 框架可能会决定销毁或者创建界面控制器, 已响应完全不受控制的某些用户操作或者事件

ViewModel 在 Fragment 中的使用.

比如在一个fragment 中通过点击 更改 viewmodel 中的一些数据:

首先放出viewModel类


class CustomViewModel : ViewModel() {

    var customName : MutableLiveData = MutableLiveData()


    init {
        customName.value = "storm"
    }

}

创建一个Framgment

创建一个fragment, 获取我们的ViewModel实例对象 通过一个按钮点击来更改viewModel 中的值

 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
       super.onViewCreated(view, savedInstanceState)


  

       val model : CustomViewModel by activityViewModels()

       btn_one.setOnClickListener{
           Log.d("storm","跳转")
          model.shareName.value = "storming"
       }

   }

创建第二个Fragment

创建另一个fragment 放置一个TextView 来显示 Custom ViewModle 中的值

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
       super.onViewCreated(view, savedInstanceState)

       val model: CustomViewModel by activityViewModels()


       model.shareName.observe(this, Observer {
           tv_content.text = it
       })
   }

Acticity

class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.activity_main)


       replaceFragment(FragmentTwo())
       btn_one.setOnClickListener {
           replaceFragment(OneFragment())
       }

       btn_two.setOnClickListener {
           replaceFragment(FragmentTwo())
       }


   }

   fun replaceFragment(fragment: Fragment) {
       val fm = supportFragmentManager
       val bt = fm.beginTransaction()

       bt.replace(R.id.fl_main, fragment)
       bt.commit()
   }

当运行之后, 首先显示的是FragmentTwo 中原始的数据
当点击切换到Fragment时点击按钮更改CustormViewModel 中的数据时, 再去切换时 就会发生变化

ViewModle 携带参数??

MainActivity 保持不动
新创建一个带参数的ViewModel

ViewModel

class CustomParamsViewModel(shareName:String) : ViewModel() {

   var shareName: MutableLiveData  = MutableLiveData()


   init {
       this.shareName.value = shareName
   }

   class CustomParamsViewModelFactory(private val shareName: String):ViewModelProvider.Factory{
       override fun  create(modelClass: Class): T {

           return CustomParamsViewModel(shareName) as T
       }

   }
}

使用ViewModelProvider的Factory 来进行构造 可以看到 内部有个内部类 实现 ViewModelProvider的Factory接口 重写create 方法 返回一个ViewModel 的实例

FragmentOne


   override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
       super.onViewCreated(view, savedInstanceState)

//        val model: CustomParamsViewModel = ViewModelProviders.of(requireActivity(),
//        CustomParamsViewModel.CustomParamsViewModelFactory("storm")).get(CustomParamsViewModel::class.java)

       val model : CustomParamsViewModel by activityViewModels {

           CustomParamsViewModel.CustomParamsViewModelFactory("storm")
       }

       btn_one.setOnClickListener{
           Log.d("storm","跳转")
          model.shareName.value = "storming"
       }

   }

FragmentTwo

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
       super.onViewCreated(view, savedInstanceState)


//        val model: CustomParamsViewModel = ViewModelProviders.of(requireActivity(),
//            CustomParamsViewModel.CustomParamsViewModelFactory("storm")).get(CustomParamsViewModel::class.java)


// 第二种获取方法 
       val model : CustomParamsViewModel by activityViewModels {

           CustomParamsViewModel.CustomParamsViewModelFactory("storm")
       }

       model.shareName.observe(this, Observer {
           tv_content.text = it
       })
   }

运行 成功!!!

你可能感兴趣的:(Android ViewModel)