본문 바로가기
IT/Android

Android] requireContext null return

by 깻잎쌈 2021. 8. 23.
반응형

https://blog.naver.com/PostView.nhn?blogId=zion830&logNo=221248961771 

 

[안드로이드] 프레그먼트에서 getContext()나 getActivity()가 null을 반환하는 오류

프레그먼트는 액티비티와 달리 Context를 상속받지 않기 때문에 바로 Context 객체를 사용할 수 없다. 그...

blog.naver.com

 

 

 override fun onAttach(context: Context) {
        super.onAttach(context)
  
        mContext = context

        if (context is Activity)
            activity = context    
}

 

https://developer.android.com/guide/components/fragments.html?hl=ko 

 

프래그먼트  |  Android 개발자  |  Android Developers

A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section

developer.android.com

주의: Fragment 내에 Context 객체가 필요한 경우, getContext()를 호출하면 됩니다. 하지만 getContext()를 호출하는 것은 프래그먼트가 액티비티에 첨부되어 있는 경우로 국한해야 한다는 점에 유의하세요. 프래그먼트가 아직 첨부되지 않았거나 수명 주기가 끝날 때 분리되었다면 getContext()는 null을 반환합니다.

반응형

댓글