Search code examples
javaandroidandroid-context

Pass Context or make use of view.getContext(). Does it really matter?


So, I have two options to get the context. See the following two methods (cleaned up for clarity) from a Utility Class.

public static void onCopyClicked(Context context, ImageView copy){
    copy.setVisibility(View.GONE);
    Intent intent = new Intent(context, NextActivity.class);
    context.startActivity(intent);
}

public static void onCopyClicked(ImageView copy){
    Context context = copy.getContext();
    copy.setVisibility(View.GONE);
    Intent intent = new Intent(context, NextActivity.class);
    context.startActivity(intent);
}

I can pass the context or simply get it from the view. I guess I prefer the second one since it is one less parameter to pass, but I wonder if the getContext() call is costly. I'm not trying to micromanage my code, but rather just trying to follow best practices (if one exists for this case).


Solution

  • You can use the second option.

    Calling getContext() on a View is not costly. The context reference is saved when a View is created and the getContext() method just returns it.

    Check the constructor source code and the getContext() method of a View.