DataBinding

DataBinding μ΄λž€

DataBinding λΌμ΄λΈŒλŸ¬λ¦¬λŠ” ν”„λ‘œκ·Έλž˜λ§€ν‹± 방식이 μ•„λ‹ˆλΌ 선언적 ν˜•μ‹μœΌλ‘œ λ ˆμ΄μ•„μ›ƒμ˜ UI κ΅¬μ„±μš”μ†Œλ₯Ό μ•±μ˜ 데이터 μ†ŒμŠ€μ™€ κ²°ν•©ν•  수 μžˆλŠ” λΌμ΄λΈŒλŸ¬λ¦¬μ΄λ‹€.

// default (ui class)
findViewById<TextView>(R.id.sample_text).apply {
    text = viewModel.userName
}

// viewBinding (ui class)
binding.sampleText.text = viewModel.userName

// dataBinding (xml)
<TextView
    android:text="@{viewModel.userName}"
    ... />

μœ„ μ˜ˆμ œλŠ” λ°μ΄ν„°λ°”μΈλ”©μ˜ 기본적인 μ‚¬μš©λ°©λ²•μ΄λ‹€. μ½”ν‹€λ¦°orμžλ°” μ½”λ“œμ—μ„œ ν…μŠ€νŠΈλ₯Ό ν• λ‹Ήν•˜λŠ”κ²Œ μ•„λ‹Œ XML νŒŒμΌμ—μ„œ ν…μŠ€νŠΈλ₯Ό ν• λ‹Ήν•œλ‹€. ν• λ‹Ή ν‘œν˜„μ‹μœΌλ‘œ @{} λ₯Ό μ‚¬μš©ν•œλ‹€.

λ ˆμ΄μ•„μ›ƒ 파일(XML) μ—μ„œ κ΅¬μ„±μš”μ†Œλ₯Ό κ²°ν•©ν•˜λ©΄ μ•‘ν‹°λΉ„ν‹°λ‚˜ ν”„λž˜κ·Έλ¨ΌνŠΈ λ‚΄μ—μ„œμ˜ UI κ΄€λ ¨ ν˜ΈμΆœμ„ 쀄일 수 μžˆμ–΄ 파일이 λ”μš± λ‹¨μˆœν™”λ˜κ³  μœ μ§€κ΄€λ¦¬ λ˜ν•œ μ‰¬μ›Œμ§„λ‹€. μ•± μ„±λŠ₯이 ν–₯μƒλ˜λ©° λ©”λͺ¨λ¦¬ λˆ„μˆ˜ 및 NPE λ₯Ό 방지 ν•  수 μžˆλ‹€.

μ‹œμž‘ν•˜κΈ°

# build.gradle(:app)

android {
    ...
    buildFeatures {
        dataBinding true
    }
}

# layout file

<layout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="viewmodel"
            type="com.myapp.data.ViewModel" />
    </data>
    <ConstraintLayout... /> <!-- UI layout's root element -->
</layout>    

Last updated