본문 바로가기
Develop/Android

Android ViewBinding에 대하여

by 라이프레이서 2021. 5. 30.
반응형

이번 포스팅에서는 findViewById를 대체하게 된 ViewBinding에 대해 알아보겠습니다.

 

❓ 왜 findViewById에서 ViewBinding으로 대체되었는가?

findViewById의 경우 layout에서 지정한 이름을 직접 가져와, 매칭 해줘야 하는 방식이었습니다. 이 과정에서 수정이 한 번 생기면 많은 부분들을 수정해줘야 했습니다. 또한 layout의 id에 접근할 때, 모든 layout에 등록된 id값을 찾아보기 때문에, 동일한 이름을 사용하는 경우 실수로 매칭이 잘못되는 경우도 발생한다는 단점이 있습니다.

 

⛏ build.gradle (Module) 설정

android {
    ...
    buildFeatures {
        viewBinding = true
    }
}

모듈 수준의 gradle파일에 위와 같이 설정해주면 viewBinding을 사용할 수 있습니다.

이렇게 해주면, 앞으로의 레이아웃에 대해 binding object를 자동으로 생성합니다. 이 object를 통해 레이아웃의 id를 갖는 view에 접근할 수 있습니다.

 

🧐 viewBinding의 사용

<androidx.constraintlayout.widget.ConstraintLayout 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".WebviewActivity">

    <WebView
        android:id="@+id/web_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

위와 같이 web_view라는 id를 같는 웹뷰가 속한 레이아웃 파일이 있습니다.

이 파일의 이름은 activity_webview.xml입니다.

 

이 상황에서 안드로이드 스튜디오는 자동으로 ActivityWebviewBinding 객체를 생성합니다. 이를 이용해야 할 Activity에서 가져다 쓸 수 있습니다. 

binding객체를 사용하여 화면을 구성하도록 하고, webview에 접근할 수 있습니다.

*참고! xml파일에서 네이밍을 web_view로 했더라도 Binding 객체는 카멜 케이스로 변환하게 됩니다.

(aaaBbbbCc와 같이, 첫 글자는 소문자로 시작하고, 의미 단위가 올 때마다 대문자로 적어주는 방법) 

 

이렇게 접근하면, findViewById의 실수를 없앨 수 있고, 보다 효율적인 프로그래밍이 가능합니다.

 

 

 

 

반응형