【问题标题】:Should I use requireContext().getString(R.string.exampleString) or getString(R.string.exampleString) inside Fragment? [duplicate]我应该在 Fragment 中使用 requireContext().getString(R.string.exampleString) 还是 getString(R.string.exampleString) ? [复制]
【发布时间】:2021-06-02 09:10:18
【问题描述】:

我应该在 Fragment 中使用 requireContext().getString(R.string.exampleString) 还是只使用 getString(R.string.exampleString)?

有区别吗?有更好的方法吗?

【问题讨论】:

标签: android


【解决方案1】:

需要上下文:

/**
     * 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 只是一个额外的调用,没有真正的价值

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多