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