728x90
๋ฐ์ํ
DataBinding๊ณผ ViewBinding์ด ๋ญ๊ฐ ๋ค๋ฅธ๊ฐ?
๊ฐ๋จํ๊ฒ ๋งํ์๋ฉด, DataBinding์ ์ด๋ฆ์ฒ๋ผ ๋ฐ์ดํฐ๋ฅผ ์ฐ๊ฒฐํด์ฃผ๋ ์ญํ ์ ํ ์ ์๋ค.
(๋ฐ์ดํฐ์ ๊ฐ์ด ๊ฒฐํฉํด์ ์ฌ์ฉํ ์ ์์)
// ์์ธํ ์ด๋ก ์ ViewBinding vs DataBinding ์ฐธ๊ณ
์ธํ
build.gradle
android {
.
..
// ์ถ๊ฐ
buildFeatures{
dataBinding = true
}
}
๋ฐ์ํ
Activity
xml
<layout></layout> ์ ์ฒด๋ฅผ ๊ฐ์ผ๋ค.
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/dataBindingTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="50sp" />
</LinearLayout>
</layout>
MainActivity.kt
class MainActivity : AppCompatActivity() {
// 1. ์ถ๊ฐ
private lateinit var binding : ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// 2. ์ถ๊ฐ
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
// ์์ ์ฝ๋
binding.dataBindingTextView.text = "๋ฐ๋ ํ
์คํธ"
}
}
Fragment
XML
<layout></layout>์ผ๋ก ์ ์ฒด ๋ ์ด์์์ ๊ฐ์ผ๋ค.
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TestFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="@+id/fragmentText"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment"
android:textSize="50sp" />
</FrameLayout>
</layout>
๋ฐ์ํ
Fragment.kt
class TestFragment : Fragment() {
// 1. ์ถ๊ฐ
lateinit var binding: FragmentTestBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// 2. ์ถ๊ฐ
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_test, container, false)
// ์์
binding.fragmentText.text = "๋ณ๊ฒฝ๋ Fragment ํ
์คํธ"
// 3. ์ถ๊ฐ
return binding.root
}
}
728x90
๋ฐ์ํ
'๐ Development > Android' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[์๋๋ก์ด๋] Kotlin-Android-Extensions(KTX) deprecated๋ ์ด์ (0) | 2023.08.13 |
---|---|
[์๋๋ก์ด๋] View Binding(๋ทฐ๋ฐ์ธ๋ฉ) ์ฌ์ฉ ๋ฐฉ๋ฒ (0) | 2023.07.17 |
[Java ์๋ฐ, Android ์๋๋ก์ด๋] ์ฑํ ๋ฐฉ ๋ง๋ค๊ธฐ (0) | 2023.07.17 |
[์๋๋ก์ด๋] Jetpack์ ViewModel์ด๋? (์ฌ์ฉ๋ฒ ์์ ) (0) | 2023.05.22 |
[์๋๋ก์ด๋] JetPack์ LiveData๋? (0) | 2023.05.22 |