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