【问题标题】:Change string from hard coded to string resources in Android Studio inside a switch statement在 switch 语句中将字符串从硬编码更改为 Android Studio 中的字符串资源
【发布时间】:2018-05-20 15:18:36
【问题描述】:

大家好,我想将 switch 语句中的字符串值从硬编码字符串更改为我在字符串资源中声明的字符串。我在片段页面适配器中。

 @Override
public CharSequence getPageTitle(int position) {
    switch (position) {

        case 0:
            return  "Museums";
        case 1:
            return "Culture";
        case 2:
            return "Food";
        default:
            return "Views";
    }
}

【问题讨论】:

    标签: android android-fragments switch-statement


    【解决方案1】:

    你可以使用string.xml文件调用字符串

    getResources().getString(int resID);

    但您不能像在片段中那样直接访问getResources()

    所以你需要通过将其作为参数传递给构造函数来获取上下文

    Context mContext; // first declare variable 
    public className(Context mContext){
        this.mContext = mContext;
    }
    

    所以最后的电话可以是mContext.getResources().getString(int resID);

    【讨论】:

    • 好,我知道现在解决了我会编辑答案谢谢@cricket_007 已编辑
    • 当我添加它来更改我的硬编码字符串时,它说无法解析方法 getActivity()
    • @Houxe 为迟到道歉,您可以在构造函数中将 Context 作为参数传递查看编辑答案
    • 非常感谢你真的帮助了我!
    • 实际上当我将它作为参数传递给 public CharSequence getPageTitle(int position, Context mContext) { } 它说它没有被父类覆盖
    猜你喜欢
    • 1970-01-01
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 2011-10-19
    • 2018-10-02
    相关资源
    最近更新 更多