Android Jetpack 之 ViewModel

定义:

在 Android 中,ViewModel 的作用就是在 UI 控制器( 如 Activity、Fragment)的生命周期中保存和管理 UI 相关的数据。ViewModel 保存的数据在配置更改(如屏幕旋转)后会依然存在,不会丢失。

优点:

  1. Activity发生屏幕旋转数据保留
  2. ViewModel + LiveData 实现 Fragment 之间共享数据
public class UserViewModel extends ViewModel {

    private MutableLiveData scoreData;

    public MutableLiveData getScoreData() {
        if(scoreData == null){
            scoreData = new MutableLiveData<>();
        }
        return scoreData;
    }
}
class FragmentA : Fragment() {

    private lateinit var userViewModel: UserViewModel

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        activity?.also {
            userViewModel = ViewModelProviders.of(it).get(UserViewModel::class.java)
        }
        return inflater.inflate(R.layout.fragment_a, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        userViewModel.scoreData.observe(viewLifecycleOwner, Observer {
            textView1.text = it.toString()
        })
    }
}
class FragmentB : Fragment() {
    private lateinit var userViewModel: UserViewModel

    private var num = 0;

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        activity?.also {
            userViewModel = ViewModelProviders.of(it).get(UserViewModel::class.java)
        }
        return inflater.inflate(R.layout.fragment_b, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        textView1.setOnClickListener {
            num++
            userViewModel.scoreData.postValue(num)
        }
        userViewModel.scoreData.observe(viewLifecycleOwner, Observer {
            textView2.text = it.toString()
        })
    }
}

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