Android Study

Android DataBinding(방법1)

85chong 2020. 8. 3. 14:36
728x90
반응형
SMALL

[테스트 환경]
- AndroiStudio 3.6.3
- Java


[준비물]
* library

* DataBindingSecondActivity.java(일반적인 Activity 만 있어도됨)
* databinding_second.xml(일반적인 xml만있으면됨)

 

!!! 중요함!!!!! Activity 상속 외의 클래스에서는 dataBinding 을 사용 할 수 없다!!

 

[Step]

1. app > build.gradle > library 코드추가 하기

- implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
- implementation 'io.reactivex.rxjava2:rxjava:2.1.3'
- implementation 'com.jakewharton.rxbinding2:rxbinding:2.1.1'


2. app > build.gradle > databinding 오픈(대소문자 정확하게 입력)

...
	android{
	...
	dataBinding{
		enabled = true
	}
...


3. 이제 사용하기위해 databinding_second.xml 오픈하여 준비해준다.

     3-1. xml 제일 바깥에 layout 으로 감싸주고, dataBinding 셋팅해준다.(Binding 할 class 셋팅)

<?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="second"
            type="com.ckck.DataBindingSecondActivity" />
    </data>


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


        <TextView
            android:id="@+id/tv_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <Button
            android:id="@+id/btn_change"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tv_text" />


    </androidx.constraintlayout.widget.ConstraintLayout>


</layout>


4. 데이터를 바인딩 시켜준다.

package com.example.studyproj.ex_databinding.ex_2;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.example.studyproj.R;
import com.example.studyproj.databinding.DatabindingSecondBinding;

public class DataBindingSecondActivity extends Activity {

    DatabindingSecondBinding binding;

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

        binding = DataBindingUtil.setContentView(this,R.layout.databinding_second);
        binding.setSecond(this);

        binding.btnChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.tvText.setText("Complete Change Text");
            }
        });
    }




}//class end


- 끝 -