일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- 오류
- 군대 깃허브
- interface
- 네트워크
- android 오류
- Status Bar
- REST API
- kotlin
- 뷰 겹침
- android studio cloud
- 군대 개발
- apollo
- log
- Rest
- BindingAdapter
- Log잘림
- okhttp
- 군대 github
- multipart
- 군대에서 안드로이드 개발
- intArray
- 군대개발
- Compose
- RETROFIT
- DataBinding
- text
- Encoding
- 디버깅 오류
- Di
- Android
- Today
- Total
KDY
Android DataBinding 본문
buildFeatures {
// 데이터 바인딩 활성화
dataBinding true
}
DataBinding 이란?
Android 생태계에서 이미 많이 사용되고 있는 DataBinding(데이터바인딩)은 간단하게 xml파일에 Data를 연결(binding)해서 사용할 수 있게 도와주며 Android JetPack 라이브러리의 하나의 기능 입니다.
즉, 데이터바인딩은 애플리케이션 로직과 레이아웃을 binding하는 데 필요한 글루 코드를 최소화합니다.
글루 코드란?프로그램의 요구사항 구현에는 기여하지 않지만, 본래 호환성이 없는 부분끼리 결합하기 위해 작동하는 코드-제타위키
내용이 이렇다 보니 findViewById를 사용하지 않아도 되며 보통 MVVM 패턴을 구현 할 때 "LiveData"와 함께 거의 필수적으로 사용합니다.
그럼 DataBinding 간단 실습을 해보겠습니다.
먼저 app단위 gradle에 아래와 같은 코드를 넣어주세요
android{
...
buildFeatures {
// 데이터 바인딩 활성화
dataBinding true
}
}
plugins{
...
id 'kotlin-kapt'
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name = "test" //변수명
type = "com.example.pratice.dataBindg.MainActivity"/> //activity가있는 파일 위치
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".dataBindg.MainActivity">
<TextView
android:id="@+id/text_binding"
android:layout_width="142dp"
android:layout_height="wrap_content"
android:text="@{test.text}" // ① Java나 Kotlin에서 객체를 사용하듯이 TextView의 text에 @{} 안에 변경될 data를 넣어줍니다.
android:textSize="50sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="클릭"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/text_binding" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
DataBinding의 최상위 레이아웃은 언제나 layout이여야 합니다.
그 후 이벤트를 만들때 참조할 데이터바인딩 변수명이 필요하니 data, vairable 태그를 추가하고 name에는 변수명을, type에는 데이터 바인딩을 통한 이벤트를 세팅할 (내 패키지명 + 액티비티 명 또는 프래그먼트 명)을 적어주면 됩니다.
MainActivity.kt
class MainActivity : AppCompatActivity() {
private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) } //DataBinding 세팅
var text = "TEST"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
// 현재 binding시킨 xml의 variable name
binding.test = this
// binding 버튼 클릭 이벤트
binding.button2.setOnClickListener {
text = "바인딩 성공"
Toast.makeText(this,"바인딩 성공",Toast.LENGTH_SHORT).show()
// Data가 변동될 경우 binding된 View들에 Data 변화를 알려줌
binding.invalidateAll()
}
}
}
실행화면
//activity
var text = "TEST"
//xml
android:text="@{test.text}"
위 부분의 코드대로 text라는 변수에 TEST 라는 글자가 입력 되있으므로 텍스트뷰에 데이터가 적용된걸 확인할 수 있습니다.
binding.button2.setOnClickListener {
text = "바인딩 성공"
Toast.makeText(this,"바인딩 성공",Toast.LENGTH_SHORT).show()
// Data가 변동될 경우 binding된 View들에 Data 변화를 알려줌
binding.invalidateAll()
}
버튼을 누를시 text 변수를 ("바인딩 성공") 으로 바꾼다는 코드입니다.
위와 같이 바뀌는걸 확인 할 수 있습니다.
'Android' 카테고리의 다른 글
Android Compose Text (0) | 2025.05.23 |
---|---|
군대에서 안드로이드 개발하기 (0) | 2025.05.21 |
Android Okhttp Logging Multipart 무시하기 (0) | 2022.09.30 |
Android BindingAdapter (0) | 2022.05.10 |
Android dp와sp의 차이 (0) | 2022.04.29 |