7

Bên trong một lớp hoạt động, tôi có lớp học này (từ mẫu android):getResources từ FragmentStatePagerAdapter

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

} 

Tôi muốn thay đổi điều này: trở lại "Tiêu đề n °" + (vị trí + 1); tới: trả về getActivity(). GetResources(). GetString (R.string.questionTabTitle) + (vị trí + 1);

Nhưng hoạt động không xác định. Làm thế nào tôi có thể nhận được tài nguyên chuỗi mà tôi cần?

Trả lời

17

Bạn có thể sửa đổi các constructor của lớp này và vượt qua bối cảnh hoạt động cha mẹ của bạn như một tham số:

private Context _context; 

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

Sau đó, trong chức năng getPageTitle của bạn, bạn có thể truy cập vào các nguồn tài nguyên sử dụng bối cảnh mới được định nghĩa trong lớp:

_context.getResources().getString(R.string.questionTabTitle) + (position + 1); 
+0

Tôi mặc dù khó khăn hơn ...: D cảm ơn! – Accollativo

Các vấn đề liên quan