2021년 1월 28일 목요일

[Android] View Binding 으로 뷰객체 쉽게 얻어오기 (android studio 3.6 부터)

 Kotlin 에서 무슨 익스텐션(synthetic binding) 써서 findViewById 대신 간편하게 뷰객체를 사용하던적이 있었다.

근데 이게 deprecated 되어버려서 쓸수없게되었다.

대신 View Binding이라는게 있어서 함 써볼라한다.


일단 build.gradle 에 viewBinding기능 쓴다고 선언해야한다.

android {
    ...
    buildFeatures {
        viewBinding true
    }
}


build.gradle 에 viewBinding있고 Android Studio 3.6 이상만 지원한다는 건 빌드과정에서 뷰객체를 찾아서 생성해준다는의미다.

따라서 빌드시에 레이아웃.xml에 없는 객체는 아예 생성안해주기 때문에 null 객체는 생성안하게 해준고 레이아웃.xml 에 정의된 타입에 맞는 객체가 생성된다. findViewById 를 쓸때는 없는 레이아웃에없는 객체id를 참조해서 에러가 났더랬다.

사용하기

        super.onCreate(savedInstanceState)

        // activity_my_best_layout.xml 파일을 불러내서 inflate한다.
        val myMainBinding = ActivityMyBestLayoutBinding.inflate(layoutInflater)

        // 레이아웃파일에 testId 로 지정된 객체를 그냥 사용할수 있다.
        myMainBinding.testId.setText("나 텍스트 객체")
        myMainBinding.button.setOnClickListener { /* ... */ }

        // myMainBinding 의 root 객체로 layout자체가 저장되기에 아래처럼 지정한다. 
        // 예전이라면 R.layout.activity_main 으로 썼어야되었겠지?

        setContentView(myMainBinding.root)

레이아웃.inflate 형태로 레이아웃파일을 불러내는건데, 레이아웃 파일은 activity_my_best_layout.xml 로 만들고 ActivityMyBestLayout+Binding 처럼 써주면 그레이들(안드스튜디오?)가 자동으로 찾아내서 biding 변수에 할당한다. 그리고 그 변수에 하위 뷰객체들이 전부 들어있으니까 그냥 id로 사용하면된다.

import ...ActivityMyBestLayoutBinding; 즉, 레이아웃이 자동으로 객체화 되어 임포트되는것을 볼수 있다.

https://developer.android.com/topic/libraries/view-binding

0 comments:

댓글 쓰기