【发布时间】:2021-06-02 09:10:18
【问题描述】:
我应该在 Fragment 中使用 requireContext().getString(R.string.exampleString) 还是只使用 getString(R.string.exampleString)?
有区别吗?有更好的方法吗?
【问题讨论】:
-
最好的方法是直接使用片段方法getString(id),不需要获取上下文。
标签: android
我应该在 Fragment 中使用 requireContext().getString(R.string.exampleString) 还是只使用 getString(R.string.exampleString)?
有区别吗?有更好的方法吗?
【问题讨论】:
标签: android
需要上下文:
/**
* Return the {@link Context} this fragment is currently associated with.
*
* @throws IllegalStateException if not currently associated with a context.
* @see #getContext()
*/
@NonNull
public final Context requireContext() {
Context context = getContext();
if (context == null) {
throw new IllegalStateException("Fragment " + this + " not attached to a context.");
}
return context;
}
获取字符串:
/**
* Return a localized string from the application's package's
* default string table.
*
* @param resId Resource id for the string
*/
@NonNull
public final String getString(@StringRes int resId) {
return getResources().getString(resId);
}
然后在 getResources 中:
/**
* Return <code>requireActivity().getResources()</code>.
*/
@NonNull
final public Resources getResources() {
return requireContext().getResources();
}
所以,在内部,它们最终都调用了 requireContext。那么还不如直接使用 getString ,其实没什么区别,使用 requireContext 只是一个额外的调用,没有真正的价值
【讨论】: