Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getResources from FragmentStatePagerAdapter

Inside an activity class, I have this class (from android samples):

    public static class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {

    public DemoCollectionPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        Fragment fragment = new QuestionFragment();
        Bundle args = new Bundle();
        args.putInt(QuestionFragment.ARG_OBJECT, i ); 
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getCount() {
        return questionList.length;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "Title n°" + (position + 1);
    }

}

I would like to change this: return "Title n°" + (position + 1); to: return getActivity().getResources().getString(R.string.questionTabTitle) + (position + 1);

But the activity is undefined. How could I get the string resource that I need?

like image 736
Accollativo Avatar asked May 25 '13 11:05

Accollativo


People also ask

What is the use of getResources () in android?

The documentation for getResources() says that it will [r]eturn a Resources instance for your application's package. In code examples I've seen this used to access the resources in res , but it seems like you can just access them directly. For example to retrieve my_string from res/values/strings.

How do I get string in adapter?

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.


1 Answers

You can modify the constructor of this class and pass the context of your parent activity as a parameter:

private Context _context; 

//Constructor of the class
public DemoCollectionPagerAdapter(FragmentManager fm, Context c) {
    super(fm);
    _context = c;
}

Then in your getPageTitle function you can access the resources using the new context defined in the class:

_context.getResources().getString(R.string.questionTabTitle) + (position + 1);
like image 83
Yoann Hercouet Avatar answered Oct 17 '22 11:10

Yoann Hercouet