ViewBinding
ViewBinding이란 findViewById를 대체하는 방식으로 findViewById 를 쓰지 않고, XML의 view component에 접근하는 object를 반환받아 view에 접근하는 방식이다.
ViewBinding을 사용하는 이유
1. findViewById를 사용할 필요가 없다.
2. Type-Safe : 레이아웃 내에서 정확한 view type를 찾아 매핑해준다.
3. Null-safety : 레이아웃에 존재하지 않는 id를 findViewById 했을 때의 NullPointException을 방지할 수 있다.
4. findViewById보다 속도가 상대적으로 빠르다.
사용법
1. gradle 추가
android {
...
viewBinding {
enabled = true
}
}
2-1. Activity에서 Binding 선언
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
바인딩 클래스 이름은 규칙이 정해져 있다.
Activity 이름 | Binding 클래스 이름 |
MainActivity | ActivityMainBinding |
SubActivity | ActivitySubBinding |
XXXActivity | ActivityXXXBinding |
2-2. Fragment에서 Binding 선언
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = FragmentSettingBinding.inflate(inflater, container, false)
return binding.root
}
3. xml에서 선언한 id 접근
binding.textView.text = "Hello, World!"
예제
'Programming > Android' 카테고리의 다른 글
[Android] Retrofit2 (0) | 2022.12.23 |
---|---|
[Android] Glide (0) | 2022.12.23 |
[Android] RecyclerView (0) | 2022.11.26 |
[Android] SQLite (0) | 2022.11.26 |
[Android] SharedPreferences (0) | 2022.11.26 |