๐Ÿ”ฅTIL๐Ÿ”ฅ์ŠคํŒŒ๋ฅดํƒ€ | ViewBinding

hyihyiยท2024๋…„ 1์›” 3์ผ
0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
26/70
post-thumbnail

๐Ÿ“–ViewBinding

ViewBinding ๊ธฐ๋Šฅ์„ ์‚ฌ์šฉํ•˜๋ฉด ๋ทฐ์™€ ์ƒํ˜ธ์ž‘์šฉํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ์‰ฝ๊ฒŒ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋ชจ๋“ˆ์—์„œ ์‚ฌ์šฉ ์„ค์ •๋œ ViewBinding์€ ๋ชจ๋“ˆ์— ์žˆ๋Š” ๊ฐ XML ๋ ˆ์ด์•„์›ƒ ํŒŒ์ผ์˜ ๊ฒฐํ•ฉ ํด๋ž˜์Šค๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. ๋ฐ”์ธ๋”ฉ ํด๋ž˜์Šค์˜ ์ธ์Šคํ„ด์Šค์—๋Š” ์ƒ์‘ํ•˜๋Š” ๋ ˆ์ด์•„์›ƒ์— ID๊ฐ€ ์žˆ๋Š” ๋ชจ๋“  ๋ทฐ์˜ ์ง์ ‘ ์ฐธ์กฐ๊ฐ€ ํฌํ•จ๋ฉ๋‹ˆ๋‹ค.

์•ž์œผ๋กœ๋Š” findViewById ๋Œ€์‹  ๋ทฐ ๋ฐ”์ธ๋”ฉ์„ ์“ฐ์ž

๐Ÿ“findViewById์™€ ViewBinding์˜ ์ฐจ์ด์ 

  1. NullSafe
    ์œ ํšจํ•˜์ง€ ์•Š์€ ๋ทฐID๋กœ ์ธํ•ด NPE ๋ฐœ์ƒ ์œ„ํ—˜์ด ์—†๋‹ค
  2. Type satefy
    ํƒ€์ž…์ด ๋‹ค๋ฅธ ๊ฒฝ์šฐ ๋ฐœ์ƒํ•˜๋Š” ์˜ค๋ฅ˜๋ฅผ ๋ฐฉ์ง€ํ•  ์ˆ˜ ์žˆ๋‹ค

๐Ÿ˜ฅViewBinding์„ ์“ฐ์ง€ ์•Š์•˜์„ ๋•Œ

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    
    val textView = findViewById<TextView>(R.id.text_view)
    val backBtn = findViewById<Button>(R.id.back_btn)
    setContentView(R.layout.activity_main)
    
    textView.text = "This is uncomfortable way"
    backBtn.setOnClickListener {
        finish()
    }
}

๐Ÿ˜šViewBinding์„ ์ผ์„ ๋•Œ

private lateinit var binding: ResultProfileBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    
    binding = ResultProfileBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)
    
    //ID๋ฅผ ํ•˜๋‚˜ํ•˜๋‚˜ ์ฐธ์กฐํ•˜์ง€ ์•Š์•„๋„ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•˜๋‹ค.
    binding.name.text = viewModel.name
    binding.button.setOnClickListener { viewModel.userClicked() }
}

๐Ÿ“ViewBinding ์‚ฌ์šฉ๋ฒ•

1) build.gradle ์„ค์ •

// ์•ˆ๋“œ๋กœ์ด๋“œ ์ŠคํŠœ๋””์˜ค 4.0 ์ด์ƒ์ผ ๋•Œ
android {
    ...
    buildFeatures {
        viewBinding = true
    }
}
// ์•ˆ๋“œ๋กœ์ด๋“œ ์ŠคํŠœ๋””์˜ค 3.6 ~ 4.0. 3.6๋ณด๋‹ค ๋‚ฎ์œผ๋ฉด ์•ˆ๋จ
android {
        ...
        viewBinding {
        	enabled true
    }
}
    

2) Activity ์„ค์ •

private lateinit var binding: ResultProfileBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    
    binding = ResultProfileBinding.inflate(layoutInflater)
    val view = binding.root //or setContentView(binding.root)
    
    setContentView(view) 
}

inflate๋Š” xml์— ์žˆ๋Š” ๋ทฐ๋ฅผ ๊ฐ์ฒดํ™”ํ•ด์ฃผ๋Š” ๊ฒƒ

๐Ÿ“Œ์ค‘์š”

๋ฐ”์ธ๋”ฉ ๊ฐ์ฒด์˜ ์ด๋ฆ„์€ ๋ ˆ์ด์•„์›ƒ ํŒŒ์ผ ์ด๋ฆ„์— 'Binding'์„ ๋ถ™์—ฌ ๋งŒ๋“ค์–ด์ง„๋‹ค.

๋ ˆ์ด์•„์›ƒ ํŒŒ์ผ ์ด๋ฆ„์ด activity_main.xml
โžก๋ฐ”์ธ๋”ฉ ํด๋ž˜์Šค์˜ ์ด๋ฆ„์€ ActivityMainBinding
๋ ˆ์ด์•„์›ƒ ํŒŒ์ผ ์ด๋ฆ„์ด fragment_home.xml
โžก๋ฐ”์ธ๋”ฉ ํด๋ž˜์Šค์˜ ์ด๋ฆ„์€ FragmentHomeBinding
profile
๋‚ด๊ฐ€ ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๊ฒŒ ์“ฐ๋Š” ๋ธ”๋กœ๊ทธ

0๊ฐœ์˜ ๋Œ“๊ธ€