ViewBinding은 xml를 자동으로 바인딩 클래스로 생성해서 xml의 view를 사용할 수 있다.
❗️ Fragment는 onCreateView에서 view를 생성하기 때문에 lifecycle이 2개 존재.
- 기본적으로 fragment는 fragment view 보다 lifecycle이 길다.
- 그래서 onDestroyView() 함수에서 직접 binding객체를 null로 만들어야 메모리 누수를 방지할 수 있다.
private var _binding: FragmentTicketCategoryBinding? = null
val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentTicketCategoryBinding.inflate(layoutInflater, container, false)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
💡 BaseFragment 만들어서 상속받기
- 초기 세팅을 Base 추상 클래스에서 구현하기.
abstract class BaseFragment<T: ViewDataBinding>(
@LayoutRes val layoutResId: Int
) : Fragment(){
private var _binding: T? = null
protected val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = DataBindingUtil.inflate(inflater, layoutResId, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.lifecycleOwner = viewLifecycleOwner
init()
}
protected abstract fun init()
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
'안드로이드' 카테고리의 다른 글
[코틀린] Paging3 (0) | 2022.10.10 |
---|---|
[안드로이드] Activity vs Fragment 차이 (0) | 2022.10.09 |
[코틀린] Coroutine Flow 개념 정리 (0) | 2022.10.06 |
[안드로이드] LiveData vs Flow 차이점 (0) | 2022.10.05 |
[안드로이드] 안드로이드 DialogFragment() 화면 사이즈 조정 (0) | 2022.10.04 |