Y_Ding

앱개발 숙련 TIL - View Binding 본문

TodayILearned/Android&Kotlin

앱개발 숙련 TIL - View Binding

YJ_ILY 2023. 8. 22. 20:05

뷰 바인딩(View Binding)

  • 뷰와 상호작용하는 코드를 쉽게 작성 가능
  • 대부분의 경우 findViewById를 대체
  • 모듈에서 사용 설정된 뷰 바인딩은 모듈에 있는 각 XML 레이아웃 파일의 결합 클래스를 생성
  • 바인딩 클래스의 인스턴스에는 상응하는 레이아웃에 ID가 있는 모든 뷰의 직접 참조가 포함

뷰 바인딩 vs findViewById

NullSafe

  • 직접 참조를 생성하므로 유효하지 않은 뷰ID로 인해 null포인터 예외가 발생할 위험이 없음
  • 레이아웃의 일부 구성에먼 뷰가 있는 경우 결합 클래스에서 참조를 포함하는 필드가 @Nullable로 표시됨

Type safety

  • 각 바인딩 클래스에 있는 필드의 유형이 XML파일에서 참조하는 뷰와 일치함
  • 클래스 변환 예외가 발생할 위험이 없음
  • 타입을 가지고 있기 때문에 타입이 다른 경우 발생하는 오류를 방지 가능

뷰바인딩 설정 방법

  • gradle에서 설정
    • Gradle Scripts -> build.gradle(Module:app)
android{
	...
    
    // AndroidStudio 3.6 ~ 4.0
    viewBinding{
    	enabled = true
    }
    
    // AndroidStudio 4.0 ~
    buildFeatures{
    	viewBinding = true
    }
}
  • Activity에서 설정
class MainActivity : AppCompatActivity() {

	//추가1
    private lateinit var binding : ActivityMainBinding
    
    override fun onCreate(savedInstanceState: Bundle?) {
    	super.onCreate(savedInstanceState)
        
        //추가2
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        
        binding.button.setOnClickListener {
        binding.textView.text = "바인딩이 잘 되었네요!"
        }
    }
}

* inflate는 xml에 있는 뷰를 객체화
* 원래는 R.layout.activity_main을 넘겨주지만 여기서는 우리가 생성한 루트 뷰를 넘겨줌


binding.button1.text = "안녕"
binding.button2.setBackgroundColor(Color.BLACK)

*위와 같이 binding된 객체 안에 있는 id에 접근하여 사용

* findViewById를 사용해도 보여지는 결과는 같음.

findViewById를 이용했을 때

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val button = findViewById<Button>(R.id.button)

        button.setOnClickListener {
            val textView = findViewById<TextView>(R.id.textView)
            textView.text = "안녕하세요!"
        }
    }
}