传递上下文或者使用view.getContext(),这真的重要吗?

huangapple go评论73阅读模式
英文:

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()方法只是返回它。

查看构造函数源代码ViewgetContext()方法

英文:

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.

huangapple
  • 本文由 发表于 2020年9月11日 06:19:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63838384.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定