我有以下方法-
public String getTitle() {
int status = getArguments().getInt(ARGS_CONTESTS_STATUS);
Context context = getContext();
if (context != null) {
switch (status) {
case ContestUtil.VAL_STATUS_NOT_OPENED:
return getContext().getResources().getString(R.string.ContestsFragment_Soon);
// return "Soon";
case ContestUtil.VAL_STATUS_RUNNING_BEGIN:
return getContext().getResources().getString(R.string.ContestsFragment_Running);
// return "Running";
case ContestUtil.VAL_STATUS_ENDED:
return getContext().getResources().getString(R.string.ContestsFragment_Winners);
// return "Ended";
}
}
return "null context";
}
总是返回“空上下文”。
我的类是一个片段类型,应该返回一个上下文,但是由于某种原因,调用此方法时上下文为null。
调用方法的唯一地方是此类,它扩展了FragmentStatePagerAdapter-
public class ContestsViewPagerAdapter extends FragmentStatePagerAdapter {
private ArrayList<? extends Fragment> mFragments;
public ContestsViewPagerAdapter(FragmentManager fm, ArrayList<? extends Fragment> fragments) {
super(fm);
mFragments = fragments;
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return 3;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return ((ContestsFragment) mFragments.get(position)).getTitle(); // <- here is the place where my method is being called
}
}
答案 0 :(得分:0)
在onViewCreated中调用getTitle函数