Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- CoordinatorLayout
- Navigation
- CustomView
- Behavior
- AppBarLayout
- DataBinding
- activity
- kotlin
- hilt
- onLayout
- notification
- ViewModel
- Android
- CollapsingToolbarLayout
- Coroutine
- 알고리즘
- BOJ
- onMeasure
- room
- LiveData
- 안드로이드
- Algorithm
- HTTP
- 알림
- 코틀린
- recyclerview
- lifecycle
- sqlite
- View
- 백준
Archives
- Today
- Total
개발일지
Android in A..Z - DataBinding (양방향 데이터 바인딩) 본문
양방향 데이터 바인딩
EditText에서 android:text="@{string}" 이런식으로 바인딩 하는 것을 단방향 바인딩이라고 한다. (Data를 EditText에 일방적으로 바인딩하는 개념)
양방향 데이터 바인딩은 EditText, RadioButton, DataPicker등 데이터가 변하는 View가 역으로 Data로 바인딩하는 것이다.
* 기본으로 지원하는 Two-Way-Databinding
LifeCycleOwner 설정하기
binding.lifecycleOwner = lifecycleOwner
ViewModel 만들기
원래 양방향 데이터 바인딩은 ObservableField를 통해 타입을 정해서 가능했지만 LiveData도 지원하기 시작했다. 이번 예제에서는 LiveData를 통해 양방향 데이터 바인딩을 진행하겠다. ViewModel과 LiveData를 구현한다.
class SearchFragmentViewModel : ViewModel() {
val search by lazy { MutableLiveData("") }
}
LiveData Observe 하기
역으로 데이터 바인딩할 때 LiveData에 Observer를 등록하여 액션을 취한다.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.search.observe(this) {
with(binding) {
textInputLayout.helperText = if (it.isBlank()) {
""
} else {
"Result of '$it'"
}
}
movieAdapter.filter(it)
}
}
양방향 데이터 바인딩
기존에 데이터 바인딩 형식은 @{} 였다면, 양방향은 @={}형식이다.
<com.google.android.material.textfield.TextInputEditText
android:text="@={viewModel.search}"
android:inputType="text"
android:background="@color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
양방향 데이터 바인딩 어뎁터 만들기
InverseMethod를 통해 만들 수 있다.
* InverseMethod에는 역으로 바인딩하는 함수의 이름을 적는다.
object Converter {
@InverseMethod("stringToDate")
@JvmStatic fun dateToString(
view: EditText, oldValue: Long,
value: Long
): String {
// Converts long to String.
}
@JvmStatic fun stringToDate(
view: EditText, oldValue: String,
value: String
): Long {
// Converts String to long.
}
}
Git (예제코드)
github.com/KangTaeJong98/Example/tree/main/Android/Databinding
KangTaeJong98/Example
My Example Code. Contribute to KangTaeJong98/Example development by creating an account on GitHub.
github.com
'Android (안드로이드) > Databinding' 카테고리의 다른 글
Android in A..Z - Databinding (문자열 서식) (0) | 2021.05.03 |
---|---|
Android in A..Z - Databinding (BindingAdapter) (0) | 2021.01.21 |
Android in A..Z - Databinding (수식) (0) | 2021.01.21 |
Android in A..Z - Databinding (바인딩 객체) (0) | 2021.01.21 |
Android in A..Z - Databinding (기본) (0) | 2021.01.21 |
Comments