Android/Kotlin

[Android][Kotlin] View Binding 뷰 바인딩이란?

yoo.o 2021. 9. 11. 02:01
반응형

View Binding이란?

Kotlin의 장점중 하나는 findViewById를 쓰지 않아도 되는 점이다. kotlin extension을 깔면 바로 접근가능했다. 그러나 코틀린 익스텐션이 deprecated됐고, 안드로이드에서도 뷰 바인딩 사용을 권장하기 때문에 공부해보려 한다.

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

 

뷰 결합  |  Android 개발자  |  Android Developers

뷰 결합 뷰 결합 기능을 사용하면 뷰와 상호작용하는 코드를 쉽게 작성할 수 있습니다. 모듈에서 사용 설정된 뷰 결합은 모듈에 있는 각 XML 레이아웃 파일의 결합 클래스를 생성합니다. 바인딩

developer.android.com

 

뷰바인딩은 뷰와 상호작용하는 코드를 쉽게 해주는 기능이다. 뷰바인딩을 허용하면 각 xml레이아웃마다 바인딩 클래스를 자동으로 생성하는데, 레이아웃에 ID가 있는 뷰에 직접 참조를 할 수 있다. 대부분의 상황에서 뷰바인딩은 findViewById를 대체한다. 

 

 

findViewByID 와의 차이점

- null 안전

Since view binding creates direct references to views, there's no risk of a null pointer exception due to an invalid view ID. 

뷰바인딩은 뷰에대한 직접적인 참조를 생성하기 때문에 잘못된 뷰아이디로 생기는 NPE가 생기지 않는다. 

 

- 유형 안전

The fields in each binding class have types matching the views they reference in the XML file. This means that there's no risk of a class cast exception.

타입을 갖고있기때문에 예를 들면 imageView에 .text 를 할 경우 생기는 오류를 방지할 수 있다는 것이다.

 

이렇게 뷰바인딩을 사용할 경우 오류가 나면 런타임이 아닌 컴파일시 빌드 실패를 알린다. 즉 개발자가 미리 알고 오류에 대응 할 수 있다는 장점이 있다. 

 

 

 

사용하는 방법

환경셋팅 - app/build.gradle에 추가

android {
    ...
    viewBinding{
        enabled = true
    }
}

 

액티비티에서 뷰 바인딩을 사용하는 경우

The name of the binding class is generated by converting the name of the XML file to Pascal case and adding the word "Binding" to the end

바인딩 클래스는 xml파일의 이름을 파스칼케이스로 바꾼 후 뒤에 Binding을 붙인 이름으로 생성된다

    private lateinit var binding: ResultProfileBinding

    override fun onCreate(savedInstanceState: Bundle) {
        super.onCreate(savedInstanceState)
        binding = ResultProfileBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
    }

뷰 참조하는 방법

binding.TextNameHere.text = ...
binding.ImgNameHere.setOnClickListener { ... }

 

 

 

 

프래그먼트에서 뷰 바인딩을 사용하는 경우

    private var _binding: ResultProfileBinding? = null
    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = ResultProfileBinding.inflate(inflater, container, false)
        val view = binding.root
        return view
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

Fragment에서는 선언시 null처리를 해줘야하고, onDestroyView에 추가 코드를 작성한다는 차이점이 있다. 

프래그먼트는 뷰보다 오래 지속되기 때문에 바인딩 클래스 인스턴스 참조를 정리해주는것이다. 

뷰 참조하는 방법은 Activity와 같다.

 

 

 

with(binding) 

뷰 바인딩을 사용할 때는 하나의 액티비티 내에서 뷰를 참조할때마다 앞에 binding을 반복해서 써줘야하는 문제가 생긴다. 

binding.tvUserName.text = ""
binding.ivUserProfile.setOnClickListener { ... }

 

이런 반복을 막기위해서는 with(binding)으로 묶어주면 된다. 

with(binding) {
	tvUserName.text = ""
	ivUserProfile.setOnClickListener { ... }
}

각각의 뷰 아이디 앞에 붙이는 binding을 생략 가능하다.

 

 

 

뷰바인딩 샘플

 

GitHub - android/architecture-components-samples: Samples for Android Architecture Components.

Samples for Android Architecture Components. . Contribute to android/architecture-components-samples development by creating an account on GitHub.

github.com

 

반응형