英文:
Pass Context or make use of view.getContext(). Does it really matter?
问题
所以,我有两个选项来获取 context。请看来自一个实用类的以下两个方法(为了清晰起见进行了清理)。
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);
}
我可以传递上下文(context),或者简单地从视图中获取它。我猜我更喜欢第二种方法,因为它少传递了一个参数,但我想知道 getContext() 调用是否昂贵。我不是要过于微观地管理我的代码,而是想遵循最佳实践(如果在这种情况下存在的话)。
英文:
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).
答案1
得分: 2
你可以使用第二个选项。
在View上调用getContext()并不昂贵。当创建View时,会保存context引用,而getContext()方法只是返回它。
查看构造函数源代码和View的getContext()方法。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论