티스토리 뷰

DataBinding

  • 레이아웃의 UI 구성요소를 앱의 데이터 소스와 결합할 수 있는 지원 라이브러리
  • UI 프레임워크 호출이 필요없어지기 때문에 파일이 단순화되고 유지보수가 쉬워짐
  • 앱 성능이 향상되며 메모리 누수 및 null 포인터 예외 방지
  • build.gradle에 라이브러리를 추가하여 사용
apply plugin: 'kotlin-kapt'

android {

    ...
    
    dataBinding {
        enabled = true
    }
}

RecyclerView에 DataBinding 적용하기 

item_news_list.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">

    <data>
    
    	<variable
            name="newsListActivity"
            type="fcmexample.dowellcomputer.myrealtripchallenge.ui.NewsListActivity" />

        <variable
            name="newsItemData"
            type="fcmexample.dowellcomputer.myrealtripchallenge.data.datasource.model.NewsItemData" />

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
		android:layout_width="match_parent"
		android:layout_height="wrap_content">

		<ImageView
			android:id="@+id/iv_item_new_list_thumbnail"
			android:layout_width="100dp"
			android:layout_height="100dp"
			android:src="@color/colorAccent"
			glideImage="@{NewsItemData.thumbnail}"
			app:layout_constraintTop_toTopOf="parent"
			app:layout_constraintStart_toStartOf="parent"
			app:layout_constraintBottom_toBottomOf="parent" />

		<TextView
			android:id="@+id/tv_item_news_list_title"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="@{NewsItemData.title}"
            android:onClick="@{()-> NewsListActivity.postUserData()}"
			android:textSize="17sp"
			app:layout_constraintStart_toEndOf="@+id/iv_item_new_list_thumbnail"
			app:layout_constraintTop_toTopOf="@id/iv_item_new_list_thumbnail" />

	</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
  • DataBinding을 쓸 xml 코드를 layout으로 감싼 후 작성
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    
...

</layout>
  • data 태그 안에 만드는 레이아웃 내에서 사용할 속성들을 변수로 만듬
<data>
        <variable //레이아웃에서 속성 값을 바로 넣어주기 위해 data 클래스를 변수로 만듬
            name="newsItemData"
            type="fcmexample.dowellcomputer.myrealtripchallenge.data.datasource.model.NewsItemData" />
</data>
  • "@{}" 에 미리 선언한 data 변수를 이용해 값을 바인딩
  • 이벤트 발생 시 임의의 데이터 바인딩 함수 실행
<TextView
	android:id="@+id/tv_item_news_list_title"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:text="@{NewsItemData.title}" //필요한 data를 text에 직접 바인딩
	android:onClick="@{()-> NewsListActivity.postUserData()}" //람다 형식으로 함수 바인딩
	android:textSize="17sp"
	android:layout_marginLeft="10dp"
	app:layout_constraintStart_toEndOf="@+id/iv_item_new_list_thumbnail"
	app:layout_constraintTop_toTopOf="@id/iv_item_new_list_thumbnail" />
  • BindingAdapter에 정의해놓은 함수들을 속성 값으로 쓸 수 있음
<ImageView
	android:id="@+id/iv_item_new_list_thumbnail"
	android:layout_width="100dp"
	android:layout_height="100dp"
	android:src="@color/colorAccent"
	glideImage="@{NewsItemData.thumbnail}" //"@{}"안에 함수의 매개변수를 담아 전달
	app:layout_constraintTop_toTopOf="parent"
	app:layout_constraintStart_toStartOf="parent"
	app:layout_constraintBottom_toBottomOf="parent" />

BindingAdpater.kt

  • xml 파일에서 속성으로 쓸 함수들을 정의하기 위한 adapter 파일
//annotation안에 들어가는 value는 xml에서 쓸 속성 값
@BindingAdapter("glideImage")
fun ImageView.setGlideImage(url: String){
    Glide.with(context)
        .load(url)
        .override(100,100)
        .centerCrop()
        .into(this)
}

NewsListAdapter.kt

  • Binding 클래스의 binding 변수를 생성하여 레이아웃 파일로 데이터를 전달
class NewsListAdapter(val context: Context) : RecyclerView.Adapter<NewsListAdapter.Holder>(){

    var data = mutableListOf<NewsItemData>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
        //레이아웃 파일명으로 생성되는 Binding 클래스로 view를 얻음
        val binding: ItemNewsListBinding = ItemNewsListBinding.inflate(LayoutInflater.from(parent.context),parent, false)
        return Holder(binding)
    }

    override fun getItemCount(): Int {
        return data.size
    }

    override fun onBindViewHolder(holder: Holder, position: Int) {
    	//xml파일의 여러 속성에 하나하나 값을 넣어줄 필요 없이 data를 통째로 xml에 전달
        holder.binding.newsItemData = data[position]
    }

    //holder의 매개변수는 binding으로 전달
    //binding.root는 view
    inner class Holder(val binding : ItemNewsListBinding) : RecyclerView.ViewHolder(binding.root) 

}

 

🕊참고자료

 

[Android] DataBinding Library 1

데이터 바인딩 라이브러리 1 참고링크 : https://developer.android.com/topic/libraries/data-binding/?hl=ko 데이터 바인딩 라이브러리는 지원 라이브러리로 Android 2.1(API 7) 이상의 모든 버전에서 사용 가능..

nobase-dev.tistory.com

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함