layout의 UI 구성요소를 앱의 데이터 소스와 결합할 수 있는 지원 라이브러리를 데바라고 한다.
Activity에서 따로 View를 정의해서 사용하지 않아도 되고 Data를 View에 연결시켜 두면 data가 변할 때 따로 새팅해 주지 않아도 변경이 될 수 있다.
버튼을 클릭했을 때 작성되어 있는 글자가 바뀌도록 만들어보겠다.
<?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">
<data>
<variable
name="mainViewModel"
type="com.example.lottieanimationtutorial.ui.MainActivity" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{mainViewModel.text}"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn_hello"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Change Text"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
package com.example.lottieanimationtutorial.ui
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.lottieanimationtutorial.R
import com.example.lottieanimationtutorial.databinding.ActivityMainBinding
import com.example.lottieanimationtutorial.utill.MainViewModel
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
var text = "Test"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.mainViewModel = this //xml에서 정의한 Name
binding.btnHello.setOnClickListener {
text = "test12"
binding.invalidateAll() //data가 변한 후 연결된 view들에 변화를 알려주는 함수
}
}
}
이렇게 코드를 짜고나면 처음 앱이 실행되었을 때 작성해둔 var text의 값인 Test가 들어가고
이후 button을 클릭했을 경우에는 test12로 바뀌는 것을 볼 수 있다.