프래그먼트 안에서 context 객체가 필요한 경우
프래그먼트 안에서 context 객체가 필요한 경우에도 2가지 경우의 상황이 있다.
- 프래그먼트가 액티비티에 붙어있는 경우
- 프래그먼트가 아직 액티비티에 붙지 않은 경우
아래 설명은 1번 상황이라고 가정하고 공식 문서에서의 설명과 stackoverflow에서 예시를 가지고 왔다.
공식 문서
https://developer.android.com/guide/components/fragments.html?hl=ko
주의: Fragment 내에 Context 객체가 필요한 경우, getContext()를 호출하면 됩니다. 하지만 getContext()를 호출하는 것은 프래그먼트가 액티비티에 첨부되어 있는 경우로 국한해야 한다는 점에 유의하세요. 프래그먼트가 아직 첨부되지 않았거나 수명 주기가 끝날 때 분리되었다면 getContext()는 null을 반환합니다.
사용법 예시
getSupportActionBar from inside of Fragment ActionBarCompat
I'm starting a new project that uses the AppCompat/ActionBarCompat in v7 support library. I'm trying to figure out how to use the getSupportActionBar from within a fragment. My activity that hosts ...
stackoverflow.com
((AppCompatActivity)getActivity()).getSupportActionBar().setSubtitle(R.string.subtitle);
이런 식으로 사용한다. 그렇지만 공식 문서에도 얘기 했듯이 프래그먼트가 액티비티에 붙어 있는 경우에만 가능한 경우다. 2번 상황인 경우는 콜백 함수인 onAttach()를 사용해야 하는데 이는 시간이 나면 추가로 작성할 예정이다.