본문 바로가기
안드로이드 스튜디오 & Kotlin

xml UI 요소 변수에 접근하는 법 - findViewById (X) -> Binding 사용하기

by 17번 일개미 2024. 11. 18.
728x90
findViewById<RecyclerView>(R.id.dataInventory)

 

기존에는 findViewById<T>() 를 사용하여 R.id. 로 접근한 요소를 사용하였지만,
이는 검색의 성능을 소모하므로, 더 좋은 방법을 사용하는 것을 공식적으로 추천한다고 한다.

 

Auto Binding 방법인데, xml 에 있는 UI 요소를 자동으로 변수처럼 접근할 수 있게 별도의 스크립트를 작성시켜주는 기능이다.

 


 

준비물은

 

1. xml 코드에서 일부 수정하기
2. build.gradles.kts 수정하기

 

두 가지이다.

 


 

xml 은 다음과 같이 수정한다.

빈 xml 을 처음 만들면, 아래와 같을텐데

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</androidx.constraintlayout.widget.ConstraintLayout>

 

여기서 두 번째 줄을 변경한다.

 

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/constraintLayout"
...
...
</layout>

 

<layout xmlns:tools= 부분을 맨 앞에 추가해주고, http 들을 해당 줄로 가져오는 것이다.

 


 

build.gradles.kts 는 buildfeatures 부분에

    buildFeatures {
        compose = true
        viewBinding = true
        dataBinding = true
    }

viewBinding = true

dataBinding = true

를 추가한다.

 

인터넷을 찾으면 여기까지 보통 나오는데 내 경우에는 되지 않았다.

dataBinding 옵션이 원인으로 보이는데

 

맨 위 plugins 에 kapt 를 추가하면 해결된다.

 

plugins {
    alias(libs.plugins.android.application)
    alias(libs.plugins.kotlin.android)
    kotlin("kapt")
}

 

 


 

 

이렇게 완료되었으면 프로젝트를 리빌드한다.

 

<xml 스크립트의 이름 + LayoutBinding> 으로 접근이 가능하다.

 

예를 들어 xml 이름이 Test 라고 하면 TestLayoutBinding 으로 선언 가능하다.

 

class MainActivity : AppCompatActivity() {

    private lateinit var testBinding: TestLayoutBinding

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

        testBinding = TestLayoutBinding.inflate(layoutInflater)
        setContentView(testBinding.root)

        testBinding.testButton.setOnClickListener{
            Log.d("MyLog", "Clicked")
        }
     }
 }

 

 

이런 식으로 사용이 가능하다.

728x90