컴공과컴맹효묘의블로그

Android- viewBinding 본문

컴퓨터/Android Studio

Android- viewBinding

효묘 2022. 3. 2. 20:49
반응형

View binding?

Activity에서 view의 값을 변경하거나 이용하고 싶을 때에는 findViewById를 이용해야 했다. view binding은 이용하고 싶은 view가 많을 때 일일이 findViewById를 하던 수고를 덜어주고자 나온 기능이다.

view binding이전에 Kotlin에서만 사용 가능한 Kotlin Synthetic이라는 기술이 있었지만, 다음과 같은 이유로 deprecated되었다.

  • 전역 네임스페이스 오염
  • 다른 layout의 동일한 id값이 존재할 경우 이를 가져오면서 NullPointerException이 발생할 가능이 있음.
  • Kotlin only

view binding은 Java에서도 사용 가능하다.

findViewByIdview binding의 비교

  • Null 안정성: 유효하지 않은 id를 가져올 경우 null오류 발생 위험
  • Type 안정성: Type을 잘못 적을 경우 type 오류 발생 위험
  • 속도: findViewById가 상대적으로 느리다.

How to use

공식문서를 참고.

참고: 뷰 결합은 Android Studio 3.6 Canary 11 이상에서 사용할 수 있다.

gradle 파일에 다음을 추가해준다.

gradle

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

혹은

android{
	buildFeatures {
        viewBinding true
    }
}

Activity

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    var width: Double? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

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

        binding.button.text = "START"
    }
}

바인딩 클래스 네임 규칙은 snake_case에서 CamelCase로 변환한 후 뒤에 Binding을 붙이면 된다.

예를 들어 activity_main이라는 layout의 binding class는 ActivityMainBinding이다.

View binding on Fragment

fragment에서는 onDestroyView에서 binding = null을 해주어야 한다. 그 이유는 fragment는 view보다 오래 살아남기 때문에 view가 destroy될 때 바인딩 클래스의 인스턴스도 같이 정리해주는 것이다.

코드 출처

class BlankFragment : Fragment() {

    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 onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.textView.text = "안녕"
    }

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

Ignore view binding

뷰 바인딩을 사용하고 싶지 않은 레이아웃에는 tools:viewBindingIgnore="true"속성을 layout에 추가해주면 된다.

<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:viewBindingIgnore="true" // 뷰 바인딩 클래스 생성을 안하고 싶을 때
    tools:context=".HelloActivity">

</androidx.constraintlayout.widget.ConstraintLayout>
참고 사이트:
반응형

'컴퓨터 > Android Studio' 카테고리의 다른 글

Android- 액션바ActionBar와 툴바Toobar  (0) 2022.03.03
Android- 플랫폼API, 제트팩 라이브러리  (0) 2022.03.03
Android- platfrom architecture  (0) 2022.03.03
Android- Permisson  (0) 2022.03.02
Kotlin  (0) 2022.03.01
Comments