【问题标题】:Accessing resources in FragmentPagerAdapter在 FragmentPagerAdapter 中访问资源
【发布时间】:2019-03-31 11:05:22
【问题描述】:

我的课程在原书sample 项目中运行良好:

private class SectionsPagerAdapter extends FragmentPagerAdapter {
    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

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

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new TopFragment();
            case 1:
                return new PizzaFragment();
            case 2:
                return new PastaFragment();
            case 3:
                return new StoresFragment();
        }
        return null;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return getResources().getText(R.string.home_tab);
            case 1:
                return getResources().getText(R.string.pizza_tab);
            case 2:
                return getResources().getText(R.string.pasta_tab);
            case 3:
                return getResources().getText(R.string.store_tab);
        }
        return null;
    }
}

Android Studio 在我新创建的项目的同一类中抱怨 getResources

error: cannot find symbol method getResources()

我注意到在工作项目中基类 FragmentPagerAdapter 指的是 som 26.0.0-alpha1 library 在不编译项目时引用28.0.0 library。

图书馆的差异会造成这样的问题吗?如何使我的新项目工作?

【问题讨论】:

  • 另外,the classthe superclass 中不存在该方法。你需要一个上下文
  • 试试getActivity().getResources().getText(R.string.pasta_tab);
  • 但我想了解为什么同一个类在原始项目中工作而文件由我创建

标签: android


【解决方案1】:

添加构造函数

private Context context;
 SectionsPagerAdapter(Context context) {
 this.context = context;
 }

所以

context.getResources();

其他

getActivity().getResources();

【讨论】:

    【解决方案2】:

    getResources() 只存在于扩展Context 基类的类中,您的类扩展FragmentPagerAdapter,这是一个适配器,而不是Context 的派生类。

    要解决此问题,您可以将此适配器包含在 ActivityFragment 中,或者扩展 Application 类并使用它来调用 getResources(),如 here 所述

    【讨论】:

      【解决方案3】:

      将您的构造函数更改为

      private Context context;
      public SectionsPagerAdapter(Context context, 
      FragmentManager fm) {
          super(fm);
          this.context = context;
      }
      

      之后,转到方法 getPageTitle 并将 getResources() 替换为 context.getResources()

      例如: context.getResources().getText(R.string.home_tab);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-08
        • 1970-01-01
        • 2020-01-31
        • 1970-01-01
        • 2011-05-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多