๊ด€๋ฆฌ ๋ฉ”๋‰ด

ruriruriya

[Android Kotlin] ์•ˆ๋“œ๋กœ์ด๋“œ ์ฝ”ํ‹€๋ฆฐ - ๋ทฐ ๋ฐ”์ธ๋”ฉ(View Binding) ๋ณธ๋ฌธ

๐Ÿค–Android/Kotlin

[Android Kotlin] ์•ˆ๋“œ๋กœ์ด๋“œ ์ฝ”ํ‹€๋ฆฐ - ๋ทฐ ๋ฐ”์ธ๋”ฉ(View Binding)

๋ฃจ๋ฆฌ์•ผใ…‘ 2024. 10. 18. 16:05
๋ฐ˜์‘ํ˜•

๋‚ด๊ฐ€ ์ƒ๊ฐํ•˜๋Š” ๋ทฐ๋ฐ”์ธ๋”ฉ์˜ ์žฅ์ ์€
๋งค๋ฒˆ findViewById๋ฅผ ์“ฐ์ง€ ์•Š์•„๋„ ๋˜๋Š” ์ ์ด๋‹ค.

๊ทธ ์™ธ์— ์ž˜๋ชป๋œ ID ์ ‘๊ทผ์ด๋‚˜ ํ˜•๋ณ‘ํ™˜ ์˜ค๋ฅ˜๋ฅผ ์ปดํŒŒ์ผ ์‹œ์ ์—์„œ ๋ฐœ๊ฒฌํ•  ์ˆ˜ ์žˆ๊ณ , MVVMํŒจํ„ด๊ณผ ์ž˜ ์–ด์šธ๋ฆฌ๋ฉฐ XML์— ๋ฐ์ดํ„ฐ์™€ ๋กœ์ง์„ ์—ฐ๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์žฅ์ ์ด ์žˆ๋‹ค.

1. build.gradle.kts(Module: app)

android {
    
    ...
    
    dataBinding {
        enable = true
    }
}

์ž‘์„ฑ ํ›„ Sync Now

2. IntroActivity

layout ํƒœ๊ทธ๋กœ ์ „์ฒด ๊ฐ์‹ธ๊ธฐ

<layout>
    <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:id="@+id/main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".auth.IntroActivity">

        ...

    </androidx.constraintlayout.widget.ConstraintLayout>
    
</layout>

 

 

3. Activity์— ๋ทฐ๋ฐ”์ธ๋”ฉ ์ƒ์„ฑ

class IntroActivity : AppCompatActivity() {

    // 1. ๋ฐ”์ธ๋”ฉ ์ƒ์„ฑ
    // ActivityIntroBinding์€ activity_intro.xml ํŒŒ์ผ๊ณผ ์—ฐ๊ฒฐ๋œ ์ž๋™ ์ƒ์„ฑ๋œ ๋ฐ”์ธ๋”ฉ ํด๋ž˜์Šค
    // lateinit var๋ฅผ ์‚ฌ์šฉํ•ด ๋‚˜์ค‘์— ๋ฐ”์ธ๋”ฉ ๊ฐ์ฒด๋ฅผ ์ดˆ๊ธฐํ™”ํ•  ์ˆ˜ ์žˆ๋„๋ก ์„ค์ •
    private lateinit var binding: ActivityIntroBinding

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

        // 2. DataBindingUtil๋กœ ๋ ˆ์ด์•„์›ƒ์„ ๋ฐ”์ธ๋”ฉ
        // DataBindingUtil.setContentView๋Š” ๋ ˆ์ด์•„์›ƒ ํŒŒ์ผ(activity_intro.xml)์„ ์ธํ”Œ๋ ˆ์ดํŠธํ•˜๊ณ ,
        // ํ•ด๋‹น ๋ ˆ์ด์•„์›ƒ๊ณผ ์—ฐ๊ฒฐ๋œ ๋ฐ”์ธ๋”ฉ ๊ฐ์ฒด(ActivityIntroBinding)๋ฅผ ์ƒ์„ฑ
        // ์ด ๋ฐ”์ธ๋”ฉ ๊ฐ์ฒด๋ฅผ ํ†ตํ•ด XML์—์„œ ์ •์˜ํ•œ UI ์š”์†Œ์— ์ง์ ‘ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค.
        binding = DataBindingUtil.setContentView(this, R.layout.activity_intro)

        // 3. UI ์š”์†Œ์— ์ ‘๊ทผํ•˜์—ฌ ํด๋ฆญ ๋ฆฌ์Šค๋„ˆ ์„ค์ •
        
        // ๋ฐ์ดํ„ฐ ๋ฐ”์ธ๋”ฉ์„ ํ†ตํ•ด XML์— ์ •์˜๋œ ๋ทฐ ์š”์†Œ๋“ค์„ ์ง์ ‘ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ.
        // ํด๋ฆญ ์ด๋ฒคํŠธ ๋ฐœ์ƒ ์‹œ LoginActivity๋กœ ํ™”๋ฉด ์ „ํ™˜
        binding.loginBtn.setOnClickListener {
            val intent = Intent(this, LoginActivity::class.java)
            startActivity(intent)
        }

        // joinBtn ํด๋ฆญ ์‹œ JoinActivity๋กœ ํ™”๋ฉด ์ „ํ™˜
        binding.joinBtn.setOnClickListener {
            val intent = Intent(this, JoinActivity::class.java)
            startActivity(intent)
        }
    }
}
๋ฐ˜์‘ํ˜•