posite 2026. 2. 22. 14:43

DataBinding

  • XML의 UI 구성 요소를 앱의 데이터와 선언적으로 결합할 수 있게 해주는 라이브러리 -> 직접 뷰에 데이터 할당
  • findViewById 제거로 보일러플레이트 코드 감소
  • 양방향 바인딩을 통해 UI 변화가 데이터에, 데이터의 변화가 UI에 즉시 반영됨
  • <layout> 태그로 XML을 감싸주어 바인딩 클래스가 자동 생성됨
  • 코드와 XML을 분리하여 비즈니스 로직과  뷰 로직을 분리
  • XML 안에 로직으 포함될 경우, 로직을 찾기 어려울 수 있음
  • LiveData 혹은 StateFlow/SharedFlow, ViewModel과 함께 사용하여 뷰의 연결을 효과적으로 관리 가능 - MVVM


예시) 

build.gradle 혹은 build.gradle.kts에서 databinding 활성화 필요

android {
    ...
    buildFeatures {
        dataBinding true
    }
}


ViewModel에서 XML과 연결할 LiveData 구성

class UserViewModel : ViewModel() {
    // 1. EditText와 연결될 변수 (사용자가 타이핑하는 대로 실시간 반영)
    val inputName = MutableLiveData<String>("")

    // 2. TextView와 연결될 변수 (버튼을 눌러야만 업데이트)
    private val _displayName = MutableLiveData<String>("이름이 여기에 표시됩니다.")
    val displayName: LiveData<String> get() = _displayName

    // 3. 버튼 클릭 시 호출될 함수
    fun applyName() {
        _displayName.value = inputName.value
    }
}


XML 구현 - ViewModel을 받아서 @{displayName}, @={intputName}(양방향 바인딩), @{() -> vm.applyName()}(이벤트) 적용

<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="vm"
            type="com.example.app.UserViewModel" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="20dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{vm.displayName}"
            android:textSize="20sp"
            android:textStyle="bold" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="이름을 입력하세요"
            android:text="@={vm.inputName}" 
            android:layout_marginTop="20dp" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="이름 적용하기"
            android:onClick="@{() -> vm.applyName()}"
            android:layout_marginTop="10dp" />

    </LinearLayout>
</layout>


Activity에서 바인딩 객체 생성 및 ViewModel 연결

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private val viewModel: UserViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 1. 바인딩 객체 생성
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        // 2. XML의 'vm' 변수에 ViewModel 할당
        binding.vm = viewModel

        // 3. LiveData가 바인딩을 통해 자동으로 UI를 갱신하도록 생명주기 주인 설정 (필수!)
        binding.lifecycleOwner = this
    }
}