class MyFragment : Fragment() { private lateinit var binding: MyFragmentBinding private lateinit var viewModel: MyViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.my_fragment, container, false)
viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
binding.viewModel = viewModel
binding.lifecycleOwner = viewLifecycleOwner // 设置lifecycleOwner
return binding.root
}
}
class MyViewModel : ViewModel() {
val text = MutableLiveData
fun updateText() {
text.value = "Hello World!"
}
}
class MyFragment : Fragment() { ... override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.text.observe(viewLifecycleOwner, Observer { text -> // 添加更新事件 binding.textView.text = text }) } }
android { ... buildFeatures { dataBinding true // 添加dataBinding功能 } }