[Kotlin] 안드로이드 데이터바인딩 사용하기

개발세발·2022년 9월 27일
0

안드로이드개발

목록 보기
1/5

DataBinding


DataBinding을 간단히 설명하면 xml 파일에 데이터를 연결(binding)해서 사용하는 것이다. Activity단에서 findViewById(...)를 통해 view를 정의하지 않아도 xml단에서 data를 view와 연동하기 때문에 값이 변경되어도 따로 수정하지 않아도 된다.


사용법


app 수준의 Build.gradle 파일 작성

android{

	...
    
    buildFeatures{
    	dataBinding true
    }
}

xml 파일 작성

xml 파일의 경우 최상단 루트를 <layout>태그로 변경하고 그 안에 <data>를 정의한다.

<?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">

    <data>
        <variable
            name="student"
            type="com.seunggyu.bindingdemo.Student" />
    </data>
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <TextView
            ...
            android:text="@{student.name}" />

        <TextView
            ...
            android:text="@{student.email}"/>
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

Student 라는 코틀린 data class와 연동해두었다.

위 코드는 학습용으로 Student 객체와 연동하기 위해 위와 같이 정의하였고
Activity와 바로 연동하기 위해서는 type="com. ... . (Activity명)"을 작성하면 된다.
ex) type="com.seunggyu.bindingdemo.MainActivity"

그리고 바인딩하고자 하는 view에는 @{ } 안에 객체를 사용하듯이 data를 넣어준다.


아래는 Student data class의 내용이다.

data class Student (
    var id:Int,
    var name:String,
    var email:String
)
  • data class의 프로퍼티는 id, name, email이다.

Activity 파일 작성

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        binding.student = getStudent()
    }

    private fun getStudent():Student{
        return Student(1,"Seunggyu","email@gmail.com")
    }
}

Activity단에서 binding 세팅을 한다.
binding을 선언할 때 xml 파일명은 Camel Case(낙타표기법)으로 변경된다.

예를들어, activity_main.xml 파일은 ActivityMain으로 변경된다.

view과 연동하기 위해서는 다음과 같이 진행한다.
id가 name_text인 TextView를 바인딩 한다면 nameText로 변경된다.
binding.nameText 로 사용할 수 있다.

profile
좋은 개발자가 되기 위한 세 걸음

0개의 댓글