这是从片段中获取字符串资源的正确方法吗? [英] Is this the right way to get string resources from within a Fragment?

查看:27
本文介绍了这是从片段中获取字符串资源的正确方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Fragment 中读取字符串资源时,哪种方法通常更好/更安全?

Which method is generally better / safer for reading string resources while in a Fragment?

这里我直接读取getResources().getString():

public class SomeFragment extends Fragment {

    public static SomeFragment newInstance() {
        Bundle args = new Bundle();
        SomeFragment fragment = new SomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String someString = getResources().getString(R.string.my_string_id);
    }

}

或者最好这样做,先设置一个 Context 字段,然后从中读取资源:

Or is it better to do it this way, by setting a Context field first and then reading the resources from that:

public class SomeFragment extends Fragment {
    private Context context;

    public static SomeFragment newInstance() {
        Bundle args = new Bundle();
        SomeFragment fragment = new SomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String someString = context.getResources().getString(R.string.my_string_id);
    }

}

这两种方法有什么权衡/缺点吗?

Any tradeoffs/drawbacks to either of these methods?

我问的原因是因为有时我会遇到第一种方法的空指针问题,但使用第二种方法可以解决;所以我不确定使用第一个是否有问题.

The reason I ask is because sometimes I've run into nullpointer issues with the first approach that were resolved by using the second approach; so I wasn't sure if it was problematic to use the first one.

推荐答案

第二种方法更复杂,与第一种方法相比没有任何价值.使用第一种方法.

The second approach is more complicated and adds no value over the first approach. Use the first approach.

这篇关于这是从片段中获取字符串资源的正确方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆