//activity_main.xml
<?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.myapplication.MyViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.appcompat.widget.AppCompatEditText
android:id="@+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@={viewModel.text}" 👈
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val viewModel: MyViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView<ActivityMainBinding?>(this, R.layout.activity_main)
.apply {
viewModel = this@MainActivity.viewModel
lifecycleOwner = this@MainActivity
}
viewModel.text.observe(this) {
Log.d("LOGGING", it)
}
}
}
class MyViewModel : ViewModel() {
val text = MutableLiveData<String>().apply { value = "" }
}
커스텀 양방향 데이터 바인딩
object BindingAdapter {
@BindingAdapter("android:text")
@JvmStatic
fun setTime(view: EditText, newValue: String) {
if (view.text.toString() != newValue) {
view.setText(newValue)
}
}
@BindingAdapter("android:textAttrChanged")
@JvmStatic
fun setListeners(
view: EditText,
attrChange: InverseBindingListener
) {
attrChange.onChange()
}
@InverseBindingAdapter(attribute = "android:text")
@JvmStatic
fun getTime(view: EditText): String {
return view.text.toString()
}
}
<androidx.appcompat.widget.AppCompatEditText
android:text="@={viewModel.text}"
android:id="@+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />