android {
dataBinding {
enabled = true
}
}
<?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="viewModel"
type="com.example.databindingexample.viewmodel.ExampleViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{viewModel.text}"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
<Button
...
android:onClick="@{ () -> viewModel.onClickButton() }"
... />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var mExampleViewModel: ExampleViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.viewModel = mExampleViewModel
binding.lifecycleOwner = this
// textview 사용하고 싶을 때 binding.textview ~ 이런 식으로 사용
}
}
}
private fun initViewModel() {
mExampleViewModel =
ViewModelProvider.AndroidViewModelFactory.getInstance(requireActivity().application)
.create(ExampleViewModel::class.java)
mExampleViewModel.BtnClickEvent.observe(viewLifecycleOwner, Observer {
// 실행 내용
})
}
class ExampleViewModel(application: Application) : AndroidViewModel(application) {
val text = MutableLiveData("")
val BtnClickEvent = SingleLiveEvent<Any>()
fun onClickButton() {
BtnClickEvent.call()
}
}
다른 것들은 Activity와 동일
class ExampleFragment : Fragment() {
private lateinit var binding: FragmentBeforeBinding
@Override
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_before, container, false)
return binding.root
}
}