在switch语句

时间:2018-05-20 15:18:36

标签: android android-fragments switch-statement

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

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

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

1 个答案:

答案 0 :(得分:0)

您可以使用

string.xml文件调用字符串
  

getResources()。getString(int resID);

但您无法像片段

那样直接访问getResources()

因此您需要通过将其作为参数传递给构造函数来获取上下文

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

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