뷰 바인딩 기능을 사용하면 뷰와 상호작용하는 코드를 쉽게 작성할 수 있다.
대부분의 경우 뷰 바인딩이 findViewById를 대체할 수 있다.
findViewById와의 차이점
1) NullSafe
2) Type safety
그럼 간단한 예제를 통해 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 사용하는게 더욱 유용할 것 같다.
맨 밑에 오늘의 일기 끝 까지 붙여주셔야 할 것 같은....느낌....ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ