【问题标题】:Resource strings as title for a tabLayout资源字符串作为 tabLayout 的标题
【发布时间】:2016-08-10 09:01:09
【问题描述】:

所以我有以下问题: 我想使用字符串数组作为 TabLayout 的标题。

在这种情况下,我使用 ViewPagerAdapter 进行布局,现在我想将选项卡的标题保存在字符串数组中。

为了提供这些标题的翻译,我使用了 2 个资源字符串,但我不能使用它们,因为字符串数组只能使用字符串,而资源字符串是整数(完美句子)。

不兼容的类型。

必需:java.lang.String

找到:int

public class ViewPagerAdapter extends FragmentPagerAdapter {

    String[] tabTitleArray = {
        R.string.dice, R.string.presets
    };

    public ViewPagerAdapter(FragmentManager manager) {

        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return null;
    }

    @Override
    public int getCount() {
        return 0;
    }
}

错误在这里:

   String[] tabTitleArray = {R.string.dice, R.string.presets};

另外:我不能使用getResource().getString();

【问题讨论】:

  • 为什么不将这些值转换为字符串而不是资源?
  • 如果你不能使用 getResources(),然后做一件事,用 FragmentManager 在你的适配器中传递你的字符串数组,并使用 getResources() 声明字符串数组
  • 最终 Stringlabels = getApplicationContext().getResources().getString(R.String.labels);

标签: java android arrays string


【解决方案1】:

一个简单的解决方案是为 ViewPagerAdapter 提供 Context 以便访问资源,例如:

public ViewPagerAdapter (FragmentManager manager, Context context) {

    super(manager);
    this.mContext = context;
}

然后

mContext.getResource().getString(....)

【讨论】:

  • @2Simpel 只是为了遵守 SO 规则,请接受已发布的答案之一或自己发布解决方案并接受它
【解决方案2】:

改用字符串数组:

<string-array name="labels">
   <item>my URL1</item>
   <item>my URL2</item>
</string-array>

并使用它:

 final String[] labels = getResources().getStringArray(R.array.labels);

【讨论】:

  • 有效但无法解析getResources()方法
  • 如果在片段中使用 getContext() 或 getActivity() 来访问 getResources().getStringArray(R.array.labels)。或者在adapter中传递activity的上下文\
  • 初始化活动/片段中的字符串数组,并像 Lino 建议的那样将其传递给适配器的构造函数
  • 我做到了 :) 感谢您的帮助
  • 如果这是您的解决方案,您能接受答案吗?我不知道所以只是猜测
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-15
  • 1970-01-01
  • 2012-06-09
  • 1970-01-01
  • 2018-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多