본문 바로가기
Android/개념 및 정보

[Context] Fragment 에서 context 와 requireContext

by Taehyung Kim, dev 2020. 12. 10.
728x90

context

    /**
     * Return the {@link Context} this fragment is currently associated with.
     *
     * @see #requireContext()
     */
    @Nullable
    public Context getContext() {
        return mHost == null ? null : mHost.getContext();
    }

requireContext

    /**
     * Return the {@link Context} this fragment is currently associated with.
     *
     * @throws IllegalStateException if not currently associated with a context.
     * @see #getContext()
     */
    @NonNull
    public final Context requireContext() {
        Context context = getContext();
        if (context == null) {
            throw new IllegalStateException("Fragment " + this + " not attached to a context.");
        }
        return context;
    }

 

둘 다 return 하는 값은 동일하다.

 

requireContext 의 특징

  • requireContext
    • 현재 context 가 null 일 경우 Exception 발생.
    • context 가 null 이 아닐 경우가 확실할 때 사용 혹은 사용할 때 throw 로 Exception 처리

 

728x90

댓글