최데브는 오늘도 프로그래밍을 한다.

Android Databinding (데이터 바인딩) 본문

Android

Android Databinding (데이터 바인딩)

최데브 2022. 2. 26. 13:35
반응형

 

Databinding  에 대해서 알아보자.

 

프로젝트에서 쓰고는 있었지만 글로 정리해본 기억은 없는 것 같아서 정리하는 시간을 가지려 한다.

databinding 을 사용하면  xml 파일에 data를 연결해서 activity에서 view를 따로 정의하지 않고도

xml에 연결해둔 곳으로 data를 전달하게 할 수 있는 장점이 있다. 

불필요한 코드가 줄어들고 MVVM 패턴에서 쓰기에 잘 어울려서 함께 쓰는 경우가 많다.

 

일단 databinding 을 사용하려면 app 수준의 Build.gradle 수정이 필요하다.

 

android {

    ...
 
    dataBinding {
        enabled = true
    }
}

//그리고 위쪽에 plugin 에도 apply plugin: 'kotlin-kapt' 라고 추가해주자.

기본 설정이 끝났다면 기존의 xml 파일을 수정해줘야한다.

databinding 을 쓰겠다고 명시해주는건데 

<?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/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"/>

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

이런식으로 가장 바깥을 <layout> 으로 감싸준다.

이렇게 해주고 나면 

private lateinit var binding: ActivityMainBinding // xml 파일명이 CamelCase 표기로 바뀌고 Binding이 붙습니다.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
}

activity 에서도 binding 을 사용해서 view를 알아 올 수 있게된다. 예를 들면 binding.textView 이런식으로.

binding 을 하나하나 선언할때마다 적어주기 귀찮다면 

 

binding.apply{

  textView.text = "최데브"

}

 

이런식으로 적고 사용할 수도 있다.

 

이것만해도 findviewbyid를 안적어도 되는게 매우 편해졌지만 이것만 하자고 데이터 바인딩을 굳이 만들지는 않았을거다.

 

xml 파일에서 data를 정의하는 부분을 알아보자.

위에 예를 들었던 xml 파일을 가져와서 위쪽에 <data> 부분과 버튼을 추가해줬다.

<?xml version="1.0" encoding="utf-8"?>

<data>

    <variable
        name="activity"
        type="com.choidev.databindingtest.MainActivity" />
</data>

<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/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{activity.text}"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"/>
            
          <Button
    		android:id="@+id/btnChange"
    		android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:onClick="{() -> activity::buttonTest()}"
    		app:layout_constraintLeft_toLeftOf="parent"
    		app:layout_constraintRight_toRightOf="parent"
    		app:layout_constraintTop_toBottomOf="@+id/text_view"
    		app:layout_constraintBottom_toBottomOf="parent"/>
    

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

그럼 activity 코드에서는 어떻게 쓰면 될까?

 

private lateinit var binding: ActivityMainBinding // xml 파일명이 CamelCase 표기로 바뀌고 Binding이 붙습니다.

var text = "test"

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
    
    binding.activity = this
}

fun buttonTest(){
	text = "test22"
}

이렇게 적어주면 

textview 의  android:text="@{activity.text}"  에  위의 activity 코드에 있는 

var text = "test" 의 값이 들어가게 되는것이고 

 

변수만 집어넣을 수 있는게 아니라 버튼의 click 이벤트도

android:onClick="{() -> activity::buttonTest}" 이런식으로 작성해주면

버튼을 클릭할때 activity 코드에 있는 fun buttonTest() 가 실행된다.

 

이렇게 databinding 을 쓰면 더 간편하고 직관적이게 데이터를 전송 할 수 있으며

ui 업데이트 관련된 코드가 줄어들어 핵심 로직에 좀 더 집중해서 코드를 짤 수 있게 된다.

 

 

 

 

반응형
Comments