7

在一个活动类中,我有这个类(来自 android 示例):

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

}

我想改变这个:return "Title n°" + (position + 1); to: return getActivity().getResources().getString(R.string.questionTabTitle) + (position + 1);

但是活动是未定义的。我怎样才能得到我需要的字符串资源?

4

1 回答 1

19

您可以修改此类的构造函数并将父活动的上下文作为参数传递:

private Context _context; 

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

然后在您的getPageTitle函数中,您可以使用类中定义的新上下文访问资源:

_context.getResources().getString(R.string.questionTabTitle) + (position + 1);
于 2013-05-25T11:29:35.587 回答