传递上下文或使用 view.getContext()。真的有关系吗?
Pass Context or make use of view.getContext(). Does it really matter?
因此,我有两种选择来获得 context
。请参阅实用工具 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);
}
我可以传递上下文或直接从视图中获取它。我想我更喜欢第二个,因为它传递的参数少了一个,但我想知道 getContext()
调用是否代价高昂。我并不是要对我的代码进行微观管理,而只是尝试遵循最佳实践(如果在这种情况下存在最佳实践)。
您可以使用第二个选项。
在 View
上调用 getContext()
并不昂贵。 context
引用在创建 View
时被保存,getContext()
方法只是 returns 它。
检查 View
的 constructor source code and the getContext()
method。
因此,我有两种选择来获得 context
。请参阅实用工具 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);
}
我可以传递上下文或直接从视图中获取它。我想我更喜欢第二个,因为它传递的参数少了一个,但我想知道 getContext()
调用是否代价高昂。我并不是要对我的代码进行微观管理,而只是尝试遵循最佳实践(如果在这种情况下存在最佳实践)。
您可以使用第二个选项。
在 View
上调用 getContext()
并不昂贵。 context
引用在创建 View
时被保存,getContext()
方法只是 returns 它。
检查 View
的 constructor source code and the getContext()
method。