findViewByid 는 View의 Id를 R클래스에서 받아와서 사용하는 방법이다.
findViewByid 보다 속도가 상대적으로 빠르다.
정확한 view의 타입을 찾아 맵핑해준다.
NullPointerException을 방지 해준다.
즉 findViewById 은 레이아웃 전체를 스캔하므로 성능 면에서 비교적 느릴 수 있고 특히 대규모 레이아웃의 경우 성능 저하가 더욱 두드러질 수 있지만, viewBinding은 레이아웃 파일에서 정의된 뷰만을 스캔하므로 성능 면에서 효율적이다.
val text = findViewById<TextView>(R.id.textView)
val text = findViewById<ImageView>(R.id.textView) //Exception
android{
...
viewBinding{
enable = true
}
}
package com.example.tutorial
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.tutorial.databinding.ActivityViewBindingBinding
class ViewBindingActivity : AppCompatActivity() {
private lateinit var binding:ActivityViewBindingBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityViewBindingBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
}
}
binding = ActivityViewBindingBinding.inflate(layoutInflater)
viewBinding 객체를 초기화 해준다.
inflate()는 xml에 있는 view를 객체화 해주는 역할을 한다.
객체화 해주는 과정에서 layouyInflater가 필요하다.
val view = binding.root
setContentView(view)