본문 바로가기

[Android/Kotlin] 안드로이드 ViewBinding 사용하기 feat. kotlin synthetics deprecated...

꿈꾸는블로그왕 2021. 1. 12.

안드로이드를 처음 접하실 때 findViewById() 메소드를 사용하여 해당 View에 접근했습니다.

하지만 프로젝트가 커지면 이는 번거로운 작업이 되었고, 또는 NullPointerException의 주범이 되곤 했습니다.

 

이러한 문제점이 있었기에 이를 해결할 수 있는 버터나이프 등 다양한 라이브러리를 사용했습니다. 하지만 코틀린으로 안드로이드 개발 할 때는 kotlin synthetics 에서 자동으로 위젯을 연결해 주어 해당 라이브러리가 필요 없었습니다.

이제는 'android-kotlin-extensions' (kotlin synthetics, parcelize) 이 Deprecated 되어 최근 안프로이드 스튜디오 버젼에서는 프로젝트 생성시 사용할 수 없습니다.

 

그래서 이번에는 findViewById()를 대체할 수 있는 ViewBinding 에 대해서 설명드립니다.

 

공식문서에서 아래와 같이 View Binding을 정의하고 있습니다.

View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module. An instance of a binding class contains direct references to all views that have an ID in the corresponding layout.

공식문서: developer.android.com/topic/libraries/view-binding?hl=en

 

사용법은 아래와 같이 간단합니다.

Gradle에 ViewBinding 추가하기

    buildFeatures {
        viewBinding = true
    }

 

Activity에서 ViewBinding 적용하기

class MainActivity : AppCompatActivity() {

    private var _binding: ActivityMainBinding? = null
    private val binding get() = _binding!!

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        _binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.btnSlideLeft.setOnClickListener {
            val intent = SlideLeftActivity.newIntent(this)
            startActivity(intent)
            slideLeft()
        }

        binding.btnSlideUp.setOnClickListener {
            val intent = SlideUpActivity.newIntent(this)
            startActivity(intent)
            slideUp()
        }
    }

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

}

MainActivity에서 적용한 모습입니다. Binding Class는 layout 파일인 activity_main.xml 네이밍 방식을 따라서  ActivityMainBinding 으로 자동 생성되고 있습니다. MainActivityBinding와 같은 이름이 마음에 들면 layout파일명의 순서를 변경해야 합니다. setContentView에 일반적으로 layout파일을 인플레이트 시키지만 여기에서는 binding 루트 뷰를 지정했습니다.

 

View에 접근하기 위헤서 Binding Class의 인스턴스를 사용하여 접근 및 하면 됩니다.

 

Fragment에서 ViewBidning 적용하기

    private var _binding: ResultProfileBinding? = null
    private val binding get() = _binding!!

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

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

 

댓글