[Android/Jetpack]ViewModel + Databinding + LiveData
2023. 2. 24. 10:02ㆍAndroid/Jetpack
728x90
반응형
구현을 위한 이전글
[프로그래밍]MVVM 패턴
MVVM패턴이란? View - ViewModel - Model View: 사용자에게 보이는 화면 ViewModel: View를 표현하기 위해 만든 View를 위한 Model && View를 나타내주기 위한 데이터 처리 담당 Model: 어플에서 사용되는 데이터 및
anovice-dp.tistory.com
[Android/Jetpack]Databinding 사용하기
(1) 기본 세팅 build.gradle (java는 아래 코드만 추가) android { ... dataBinding { enabled = true } ... } build.gradle (kotlin의 경우, 아래 코드도 추가) apply plugin: 'kotlin-kapt' ... dependencies { ... // 버전은 본인 gradle 버
anovice-dp.tistory.com
[Android/Jetpack]LiveData
LiveData란? 식별 가능한 데이터 홀더 클래스. 스스로 수명주기를 인식함 Data의 변경을 관찰할 수 있는 Data Holder 클래스 UI와 데이터 상태의 일치 보장 메모리 누출이 없음 비정상 종료가 없음 수명
anovice-dp.tistory.com
Gradle 세팅
apply plugin: 'kotlin-kapt'
android {
...
buildFeatures{
dataBinding true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
// For Kotlin projects
kotlinOptions {
jvmTarget = "1.8"
}
}
dependencies{
...
def lifecycle_version = "2.2.0"
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
implementation "androidx.activity:activity-ktx:1.1.0"
}
MainViewModel.kt
class MainViewModel():ViewModel(){
// LiveData
// 값이 변경되는 경우 MutableLiveData로 선언한다.
var count = MutableLiveData<Int>()
init {
count.value = 0
}
fun increase(){
count.value = count.value?.plus(1)
}
fun decrease(){
count.value = count.value?.minus(1)
}
}
- ViewModel안에 LiveData가 있는 모습
- LiveData 객체의 값이 변경될 경우에는 MutableLiveData()으로 선언
- increase(), decrease() 함수를 선언 해 각각 값이 증가/감소하는 역할의 함수
<com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/fab_plus" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="@{()->viewModel.increase()}" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:srcCompat="@drawable/ic_baseline_exposure_plus_1_24" />
728x90
반응형
'Android > Jetpack' 카테고리의 다른 글
Jetpack Compose에서 remember vs rememberSaveable 차이 완벽 정리 (0) | 2025.02.13 |
---|---|
Android Studio에서 Proto DataStore 설정하는 방법 (gradle kotlin) (0) | 2024.11.07 |
Preference DataStore와 Proto DataStore의 차이 (0) | 2024.11.05 |
[Android/Jetpack]LiveData (0) | 2023.02.24 |
[Android/Jetpack]Databinding 사용하기 (0) | 2023.02.24 |