티스토리 뷰

Programming/Android

ViewBinding vs DataBinding

Mongi0417 2023. 6. 27. 20:23

View Binding

먼저, 안드로이드 개발 문서에서 정의하는 View Binding은 아래와 같다.

View Binding을 사용하면 뷰와 상호작용하는 코드를 쉽게 작성할 수 있습니다. 모듈에서 사용 설정된 View Binding은 모듈에 있는 각 XML 레이아웃 파일의 Binding Class를 생성합니다. Binding Class의 인스턴스에는 상응하는 레이아웃에 ID가 있는 모든 뷰의 직접 참조가 포함됩니다.

 

요약하자면, findViewById() 메소드를 사용하지 않고 Binding 객체를 통해 모든 View에 접근할 수 있다는 의미로 해석된다.

 

기존 View 접근 방식은, 모든 뷰에 대해 findViewById() 메소드를 통해 객체를 생성하여야 한다.

10개의 View가 존재한다면 findViewById() 메소드를 10번 사용해야 하고, 100개의 View가 존재한다면 100번 사용해야 한다.

 

View binding 장점

1. 긴 코드 작성을 피해 코드의 유지 보수가 편리해지고

2. 유효하지 않은 View ID로 인한 NullPointerException 발생을 방지하고

3. 각 Binding Class에 있는 필드의 유형이 XML 파일에서 참조하는 뷰와 일치한다. 즉, ClassCastException 예외가 발생할 위험이 없다.

 

View Binding 사용하기

build.gradle 추가

android {
    ...
    buildFeatures {
        viewBinding true
    }
}

액티비티에서 View Binding 사용

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        
        binding.tvHello.setText("New Hello World!");
    }
}

activity_main.xml에서 TextView의 ID는 tvHello이고 binding.tvHello.setText를 통해 TextView의 텍스트를 변경해주었다.


Data Binding

프로그래매틱 방식이 아니라 선언적 형식으로 레이아웃의 UI 구성요소를 앱의 데이터 소스와 결합할 수 있는 지원 라이브러리를 의미한다.

프로그래매틱 방식(프로그래밍 방식)

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = findViewById(R.id.textView);
        textView.setText("Hello, new World!");
    }
}

선언적 방식

<TextView
        android:text="@{viewmodel.userName}" />

레이아웃은 흔히 UI 프레임워크 메소드를 호출하는 코드가 포함된 액티비티에서 정의된다.

예를 들어, 프로그래밍 방식으로 findViewById() 메소드를 통해 위젯을 찾아 객체와 연결하고 setText 메소드를 통해 텍스트를 할당한다.

하지만 선언적 방식을 활용하면 자바 코드를 호출할 필요 없이 레이아웃 파일에서 직접 위젯에 텍스트를 할당할 수 있다. 이처럼, 데이터와 뷰의 연결 작업을 레이아웃 파일에서 처리하는 방식을 Data Binding이라 한다.

Data Binding을 통해 액티비티에서 많은 양의 UI 프레임워크 호출을 제거할 수 있기 때문에 파일이 단순화되고 유지관리 또한 쉬워진다. 또한 앱 성능이 향상되고 메모리 누수 및 NullPointerException을 방지할 수 있다.

 

Data Binding 사용하기

build.gradle 추가하기

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

액티비티에서 Data Binding 사용하기

1. 뷰에 보여줄 Class 선언

public class User {
    private String userName;

    public User(String userName) {
        this.userName = userName;
    }

    public String getUserName() {
        return userName;
    }
}

2. xml 파일에서 <layout> 태그 안에 레이아웃 작성

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <variable
            name="user"
            type="com.example.test.User"/>
    </data>

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

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{user.userName}"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"/>
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

<data> 태그 내에서 여러 <variable> 태그를 사용할 수 있다. 각 <variable> 태그는 레이아웃 파일 내 결합 표현식에 사용될 레이아웃에서 설정할 수 있는 속성을 설명한다. 즉, 데이터와 뷰를 연결하는 태그이며 name = 사용할 이름, type = 연결할 데이터가 있는 경로를 나타낸다.

TextView의 text 속성에는 표현식 @{} 구문을 통해 작성하는데, "@{name.name 내의 속성}"으로 작성한다.위 코드에서는 user 변수의 userName 속성으로 설정된다.표현식에서 name 내의 속성의 접근 제어자가 private이라면 자동으로 getter 메소드에 접근한다.

자동으로 getter에 접근

3. 액티비티 작성하기

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        User user = new User("Mongi0417");
        binding.setUser(user);
        // setUser 메소드는 setter 메소드를 의미한다.
    }

DataBindingUtil 클래스의 setContentView 메소드를 통해 xml 파일과 결합한 뒤, user 객체의 데이터를 xml의 <data> 태그의 <variable> 내부에 있는 name에 결합한다.

 

양방향 Data Binding

단방향 Data Binding

단방향 Data Binding은 기존 

양방향 Data Binding

 

View Binding과 Data Binding의 차이

View Binding 장점:

1. 빠른 컴파일: View Binding은 @annotation 처리가 필요하지 않기 때문에 컴파일 시간이 더 짧다.

2. 사용 편의성: View Binding은 특별한 태그가 필요하지 않기 때문에 더 빠르게 실행된다.

View Binding 단점:

1. 레이아웃 변수나 표현식을 지원하지 않기 때문에 동적 UI 콘텐츠를 선언하는 것이 불가능하다.

2. 양방향 Data Binding을 지원하지 않는다.

 

결과적으로 단순히 findViewById를 대체하기 위해서는 View Binding을 사용하는 것이 훨씬 효율적이다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   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
글 보관함