Android-MVVM-Databinding-Retrofit2/MainActivity.java at master · codingspecialist/Android-MVVM-Databinding-Retrofit2

DA6204C0-EA1C-4324-A814-C1FB2B7848F6.png

C5AF5197-97F3-49B8-9676-D925C98736C8.png

gradle

def lifecycle_version = "2.4.0-alpha03"
def arch_version = "2.1.0"

// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"

코틀린

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.4.0-alpha03"
		def arch_version = "2.1.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"
}

예시

액티비티에서 관리할 데이터

public class Note {

    private int id;
    private String title;
    private String content;
}

액티비티를 관리하는 view model

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

public class MainViewModel extends ViewModel {

    // 변할 수 있는 데이터
    private MutableLiveData<Note> note = new MutableLiveData<>();

    // 데이터 초기화
    public void init(){
        note.setValue(new Note(1, "제목", "내용"));
    }

    // 옵저버로 지켜보려면 return 해야함
    public MutableLiveData<Note> getNote(){
        return note;
    }

    public void updateNote(){
        note.setValue(new Note(2, "제목 변경", "내용 변경"));
    }
}