David
David

Reputation: 75

When should I use getActivity() and getContext() from a Fragment?

I was wondering when should I use getActivity() and getContext() from a Fragment? and why not using getActivity always. Is there any situation where getActivity could fail?

Upvotes: 2

Views: 2601

Answers (1)

Submersed
Submersed

Reputation: 8870

Not sure there is a getActivityContext() method, but as far as the difference between getContext() and getActivity(), there really isn't one other than the type you get back from the call. From the source the v4 Fragment, it's just a convenience method that casts the Context to an Activity or FragmentActivity before returning, and it's similar for the normal Fragment class.

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

/**
 * Return the {@link FragmentActivity} this fragment is currently associated with.
 * May return {@code null} if the fragment is associated with a {@link Context}
 * instead.
 */
final public FragmentActivity getActivity() {
    return mHost == null ? null : (FragmentActivity) mHost.getActivity();
}

Also, an Activity is a Context, so there's not much of a difference.

Upvotes: 3

Related Questions