在FragmentPagerAdapter中访问资源

时间:2019-03-31 11:05:23

标签: android

我有一个在原著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库在未编译项目时是指28.0.0库。

库的差异可能会造成这样的问题吗?如何使我的新项目正常工作?

3 个答案:

答案 0 :(得分:1)

添加构造函数

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

所以

context.getResources();

其他

getActivity().getResources();

答案 1 :(得分:0)

select EventDate, DateOfExpense, DateOfPayment, DateSold, Income, Expense, Bill, sum(Income - Expense - Bill) over (order by EventDate rows between unbounded preceding and 1 preceding) Opening, sum(Income - Expense - Bill) over (order by EventDate) Closing from ( select coalesce(coalesce(DateOfPayment, DateOfExpense), DateSold) EventDate, * from ( select DateOfPayment, sum(coalesce(Bill, 0)) Bill from @SupplierPayments group by DateOfPayment ) sp full join ( select DateOfExpense, sum(coalesce(Expense, 0)) Expense from @Expensis group by DateOfExpense ) e on sp.DateOfPayment = e.DateOfExpense full join ( select DateSold, sum(coalesce(Income, 0)) Income from @Income group by DateSold ) i on sp.DateOfPayment = i.DateSold ) a order by EventDate 仅存在于扩展getResources()基类的类中,您的类扩展了Context,它是一个适配器,而不是FragmentPagerAdapter的派生类。

要解决此问题,您可以将此适配器包括在ContextActivity内,或者扩展Application类并按照here的说明使用它来调用Fragment < / p>

答案 2 :(得分:0)

将构造函数更改为

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);