안드로이드 스튜디오 3.0에서 kotlin을 정식지원 해주기 때문에 겉핥기를 하고 있는데, 생각보다 쉽게 적응할 수 있을 것 같다.
그런 의미에서 일단 MVVM 예제를 만들어 봤는데, 크게 달라진 게 없는 것 같다.
build.gradle 은 딱 기존 데이터바인딩 설정에 비해 두 줄이 추가돼야한다.
. . . apply plugin: 'kotlin-kapt' . . android { . . dataBinding.enabled true compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } . . } dependencies { . . . kapt 'com.android.databinding:compiler:3.0.0' . . }
MainActivity는 kotlin 형식으로 바꿔주면 된다.
class MainActivity : AppCompatActivity() { private val activityModel = MainActivityModel() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding: MainActivityBinding = DataBindingUtil.setContentView(this, R.layout.main_activity) binding.model = activityModel activityModel.onCreate() } }
뷰모델도 kotlin 형식으로 바꿔주면 끝.
class MainActivityModel { val hello = ObservableField<String>() fun onCreate() { hello.set("hello") } }
레이아웃은 기존과 똑같다.
<layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <data> <variable name="model" type="kr.susemi99.testkotlin.MainActivityModel"/> </data> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{model.hello}" tools:text="hello world!!!"/> </LinearLayout> </layout>
코틀린 형식으로 적당히 잘 바꿔주면 MVVM도 쉽게 변환이 될 것 같다.