How to get String Resource within ViewPager Adapter?

后端 未结 9 1830
孤城傲影
孤城傲影 2020-12-31 07:42

I trying to set the title for my viewpager, I can\'t seem to get it to work. I tried Resources.getSystem().getString(R.string.title1); and also tried to pass a context. Coul

相关标签:
9条回答
  • 2020-12-31 08:41

    you should call getString from an activity's context, change your code to

    public class ViewPagerAdapter extends FragmentPagerAdapter {
        final int PAGE_COUNT = 3;
        Context context;
    
        public ViewPagerAdapter(FragmentManager fm, Context nContext) {
            super(fm);
            context = nContext;
        }
    
        @Override
        public int getCount() {
            return PAGE_COUNT;
        }
    
        @Override
        public Fragment getItem(int position) {
            return PageFragment.create(position + 1);
        }
    
        @Override
        public CharSequence getPageTitle(int position) {
    
            switch (position) {
    
            case 0:
                return context.getString(R.string.title1);
    
            case 1:
                return context.getString(R.string.title1);
    
            case 2:
                return context.getString(R.string.title1);
            }
    
            return null;
        }
    }
    
    0 讨论(0)
  • 2020-12-31 08:46

    If it is not allowed to call getResources() in your viewPager Adapter, you need to declare it as a static variable in the parent activity

    0 讨论(0)
  • 2020-12-31 08:47

    If you are trying to access string resources from outside of an activity, then you need to pass the context in to that class (which you stated you have already done), and then call

    String str = context.getResources().getString(R.string.some_string);
    

    Also check your strings.xml file to make sure that you are using the string id correctly. If you're using android studio you should be able to simply start typing R.string. and it will then show suggestions from the strings.xml file. If you do not see your resource here, then that may indicate a problem with the way you are storing your resources, as opposed to how you are trying to access them.

    0 讨论(0)
提交回复
热议问题