본문 바로가기
안드로이드 자바

[Java][Android] 데이터바인딩 활용 예시 만들기

by teamnova 2025. 5. 2.
728x90

오늘은 데이터바인딩 라이브러리를 활용해 간단한 UI 정보 변경 예시를 만들어 보겠습니다.

 

안드로이드 데이터 바인딩 라이브러리는 XML UI 구성요소의 데이터를 선언적 형식을 사용해 소스코드 측 데이터와 결합하여 한쪽이 데이터 변경시 나머지 한쪽의 데이터를 자동 변경시키도록 동기화 시켜주는 기능을 제공하는 라이브러리 입니다.

 

 

 

그래들 설정

=> 모듈 수준의 build.gradle 파일 에서 android{ } 블록 내에 위 이미지와 같이 입력하여 databinding 기능을 활성화 시켜주세요.

 

 

 

 

레이아웃 xml 파일 코드(activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>
        <variable
            name="product"
            type="만든 프로젝트 패키지명.Product" />
            <!--        ex) com.example.databinding_example.Product-->
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="16dp">

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

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{product.price}"
            android:textSize="16sp"
            android:layout_marginTop="8dp" />

        <Button
            android:id="@+id/updateButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="상품 정보 업데이트"
            android:layout_marginTop="16dp" />

    </LinearLayout>
</layout>



 

액티비티 자바 코드

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;
    private Product product;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 데이터 바인딩 설정
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        // 상품 객체 생성
        product = new Product("스마트폰", "899,000원");

        // 바인딩 객체에 상품 설정
        binding.setProduct(product);

        // 버튼 클릭 리스너 설정
        binding.updateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 상품 정보 업데이트
                product.setName("태블릿");
                product.setPrice("599,000원");

                // 바인딩 갱신
                binding.invalidateAll();
            }
        });
    }
}



 

데이터 보관용 클래스

// 간단한 상품 정보 클래스
public class Product {
    private String name;
    private String price;

    public Product(String name, String price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }
}



 

 

실행 결과

 

 

UI 정보가 변경된 것을 확인할 수 있습니다.