[TIL] ๐ŸŒผ24/04/26๐ŸŒผ#Hilt์—์„œ Fragment์˜ context ๊ฐ€์ ธ์˜ค๊ธฐ

0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
88/104
post-thumbnail
post-custom-banner

[TIL] ๐ŸŒผ24/04/26๐ŸŒผ#Hilt์—์„œ Fragment์˜ context ๊ฐ€์ ธ์˜ค๊ธฐ

Hilt์—์„œ Fragment์˜ context ๊ฐ€์ ธ์˜ค๊ธฐ

๐Ÿ“Œ์ฐธ๊ณ ์ž๋ฃŒ

  • Hilt๋ฅผ ์ ์šฉํ•˜๊ธฐ ์ „ Fragment์—์„œ Context๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ์ฝ”๋“œ
    (Dialog๋ฅผ ๋„์šฐ๊ธฐ ์œ„ํ•ด AppCompatActivity ํƒ€์ž…์˜ context๋ฅผ ๋„˜๊ฒจ์คŒ)
val addDialog = AddFolderDialog(binding.root.context as AppCompatActivity)
  • Hilt์—์„œ๋Š” Fragment์—์„œ Context๋ฅผ ๊ฐ€์ ธ์˜ฌ ๋•Œ ViewComponentMAnager๊ฐ€ ๊ด€๋ฆฌํ•˜๋Š” FragmentContextWrapper๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค
    -> AppCompatActivity ํƒ€์ž…์œผ๋กœ cast ๋ถˆ๊ฐ€
    -> Fragment์˜ Activity์˜ Context๋ฅผ ๊ฐ€์ ธ์˜ค๊ธฐ ์œ„ํ•ด context.getBaseContext()๋ฅผ ์‚ฌ์šฉํ•ด์•ผ
private fun getActivityContext(): Context {
    val context = binding.root.context
    return if (context is ViewComponentManager.FragmentContextWrapper) context.baseContext
    else context
}
val addDialog = AddFolderDialog(getActivityContext() as AppCompatActivity)
post-custom-banner

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