(kotlin) ViewBinding

박용석·2023년 8월 23일
0

뷰바인딩

뷰 바인딩 기능을 사용하면 뷰와 상호작용하는 코드를 쉽게 작성할 수 있다.
대부분의 경우 뷰 바인딩이 findViewById를 대체할 수 있다.

findViewById와의 차이점

1) NullSafe

  • 뷰 바인딩은 뷰의 Direct References 즉 직접 참조를 생성하므로 유효하지 않은 뷰ID로 인해 null포인터 예외(NPE)가 발생 할 위험이 없다.

2) Type safety

  • 각 바인딩 클래스에 있는 필드의 유형이 XML파일에서 참조하는 뷰와 일치한다.
  • 즉,클래스 변환 예외가 발생할 위험이 없다.

그럼 간단한 예제를 통해 findViewById를 대체하여 어떻게 사용하는지 알아보자

gradle 설정

android{
	...
    
    // AndroidStudio 3.6 ~ 4.0
    viewBinding{
    	enabled = true
    }
    
    // AndroidStudio 4.0 ~
    buildFeatures{
    	viewBinding = true
    }
}

main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity">

    <TextView
        android:id="@+id/myTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="Button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/myTextView" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

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

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

        binding.myButton.setOnClickListener{
            binding.myTextView.text = "바인딩이 잘 되네요!"
        }
    }
}

findViewById를 사용하지 않고 ViewBinding으로 직접 참조하여 간단하게 binding. 으로 xml file의 아이디를 불러와서 사용할 수 있다. 변수가 많아질수록 ViewBinding 사용하는게 더욱 유용할 것 같다.

profile
슬기로운 개발 활동

2개의 댓글

comment-user-thumbnail
2023년 8월 24일

맨 밑에 오늘의 일기 끝 까지 붙여주셔야 할 것 같은....느낌....ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ

답글 달기
comment-user-thumbnail
2023년 8월 24일

코드를 작성 때 ''' 옆에 kotlin을 붙여주시면 색깔이 살아납니다...

예시
'''kotlin
로직
'''

답글 달기