PROGRAMMING/Android

[JETPACK_Android View] Databinding과 dataclass

2023. 3. 6. 21:55
목차
  1. 1 DataBinding

1 DataBinding

  - 이름처럼 데이터의 연결 역할을 수행하게 해보자 

  - 데이터 결합

    // build.gradle에 databinding 추가!
    
    buildFeatures{
        dataBinding = true
    }

 

- Person 데이터 클래스 생성하고, xml 상에서 데이터 <variable> 세팅

//activity_main.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"
        xmlns:tools="http://schemas.android.com/tools">

        <data>
                <variable
                    name="user"
                    type="com.jetpack.Person" />
        </data>

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".MainActivity">

                <TextView
                    android:id="@+id/dataBindingEx"
                    android:textSize="50sp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hello World!"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintRight_toRightOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

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

data class Person (
    val name : String,
    val age : Int
)

 

(1) 기존에 사용했던 Binding

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.dataBindingEx.text = "변경된 텍스트"
    }
}

 

(2) DataBinding의 데이터 결합 사용

 - 데이터 바인딩으로 data class를 바로 불러와서 사용할 수 있음

 - onClick 이벤트를 바인딩과 결합해서 사용

<?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="user"
                    type="com.jetpack.Person" />
        </data>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".MainActivity">

                <TextView
                    android:textSize="50sp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@{user.name}" />

                <TextView
                    android:textSize="50sp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@{Integer.toString(user.age)}" />

                <Button
                    android:text="btn"
                    android:onClick="myClick"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>

        </LinearLayout>
</layout>
class MainActivity : AppCompatActivity() {

    // 데이터 바인딩 선언
    private lateinit var binding : ActivityMainBinding
    var testCount = 20

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        //xml에서 정의한 user를 person에 결험
        val person = Person("개복치", 20)
        binding.user = person
    }

    fun myClick(view : View){
        Log.d("MainActivity", "onClick")
        testCount ++

        val person = Person("개복치", testCount)
        binding.user = person
    }
}

 

(2) DataBinding의 데이터 결합 사용

 - TextView에 데이터바인딩을 사용해 로직을 걸어 사용

                <TextView
                    android:textSize="50sp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@{user.age > 30 ? `나이 많음` : `나이 적음`}" />

  1. 1 DataBinding
'PROGRAMMING/Android' 카테고리의 다른 글
  • [JETPACK_Android View] Adapter + ViewBinding
  • [JETPACK_Android View] DataBinding
  • [JETPACK_Android View] ViewBinding
  • [JETPACK_Android View] Kotlin Extensions
yuujoeng
yuujoeng
IT and Information Security
yuujoeng
알감자는 공부중
yuujoeng
전체
오늘
어제
  • 🎁 (201)
    • SECURITY (80)
      • 관리보안 (27)
      • System (10)
      • System | Wargame (30)
      • Android (9)
      • Reversing (3)
      • AWS (1)
    • BLOCKCHAIN (45)
      • BlockChain (22)
      • Ethereum (23)
    • PROGRAMMING (30)
      • Web (16)
      • Android (6)
      • Spring (8)
    • IT (0)
      • Article (40)
      • RaspberryPi (5)

블로그 메뉴

  • HOME
  • TIKKLE

인기 글

hELLO · Designed By 정상우.
yuujoeng
[JETPACK_Android View] Databinding과 dataclass
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.