이전 게시글 1)
[Android/안드로이드]DataBinding 기본 예제
1. gradle(app) android{ dataBinding{ enabled=true applyplugin:'kotlin-kapt'//코틀린 사용시 추가 } } 2. xml 으로 감싸주기 3. 코드 작성 class MainActivity : AppC..
leehochang.tistory.com
이전 게시글 2)
[Android/안드로이드]ViewModel 기본 예제
이전 게시글 :https://leehochang.tistory.com/5 3. 코드 작성 class MainActivity : AppC.." data-og-host="leehochang.tistory.com" data-og-source-url="https://leehochang.tistory.com/5" data-og-url="https..
leehochang.tistory.com
1. 필요성
1) UI와 데이터 일치를 보장
LivaData의 데이터 변경시 Observer에게 알리게 된다. 그래서 Observer의 onChanged() 메소드 내에서 UI 변경 코드를 넣어 UI 처리를 통합적으로 컨트롤할 수 있다.
2) 생명 주기 연동
생명 주기가 자동으로 관리된다. 이로 인해 가지는 몇가지 장점이 있다.
- 생명 주기에 따라 최신 데이터 유지 ( 비활 -> 활성화, 화면 회전 등 )
- 생명 주기가 끝나면 Observer는 자동으로 삭제 ( 메모리 누수 방지 )
- 생명 주기 비활성시 Observer는 어떠한 이벤트도 받지 않는다
3) 리소스 공유
LiveData 객체는 싱글톤 패턴을 사용한다. 이를 확장해 모든 Observer가 LiveData 객체에 접근 가능
2. gradle ( app )
dependencies {
def lifecycle_version = "2.3.1"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
}
3. 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">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/i_count_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="70sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
<Button
android:id="@+id/i_btn_increase"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="++"
android:textSize="40sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"/>
<Button
android:id="@+id/i_btn_decrease"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="--"
android:textSize="40sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
4. viewModel에서 LiveData 등록
class CounterViewModel : ViewModel() {
var counter : MutableLiveData<Int> = MutableLiveData()
init {
counter.value = 0
}
fun increase(){
counter.value = counter.value!! + 1
}
fun decrease(){
counter.value = counter.value!! - 1
}
}
5. Observer 내에서 UI 처리
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val binding : ActivityMainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main)
val counterViewModel : CounterViewModel by viewModels()
binding.iBtnIncrease.setOnClickListener {
counterViewModel.increase()
}
binding.iBtnDecrease.setOnClickListener {
counterViewModel.decrease()
}
counterViewModel.counter.observe(this, Observer {
int -> binding.iCountText.text = int.toString()
})
}
}
6. 시연
'안드로이드 > 디자인 패턴' 카테고리의 다른 글
[Android/안드로이드] 왜 MVP/MVVM을 사용해야 하는가? (feat. mvc,mvp,mvvm, acc를 활용한 mvvm 구현 예제 ) (0) | 2021.07.20 |
---|---|
[Android/안드로이드]ViewModel 기본 예제 (0) | 2021.06.18 |
[Android/안드로이드]DataBinding 기본 예제 (0) | 2021.06.17 |