getPageTitle()的空对象引用

时间:2015-04-10 10:53:51

标签: android fragment adapter pager

我需要在FragmentPagerAdapter中使用getPageTitle来正确地包含滑动标签,但我目前还有一些问题。

这是我的代码:

public class TabsPagerAdapter extends FragmentPagerAdapter {

private FragmentActivity activity;
//private Context context;

public static final int[] TITLES = { R.string.popularsongs, R.string.lastalbums };

public TabsPagerAdapter(FragmentManager fm) {
    super(fm);
    this.activity = activity;
}

@Override
public Fragment getItem(int index) {

    switch (index) {
        case 0:
            // Top Rated fragment activity
            return new ArtistPopularFragment();
        case 1:
            // Games fragment activity
            return new ArtistAlbumsFragment();
    }

    return null;
}

@Override
public int getCount() {
    // get item count - equal to number of tabs
    return 2;
}

@Override
public CharSequence getPageTitle(int position)
{
    /*
    String s = activity.getResources().getStringArray(R.array.tab_titles_artist);
    CharSequence cs = s;
    return cs; */
    return activity.getResources().getText(TITLES[position]);
}

}

使用此代码会导致应用崩溃。我该如何解决这个问题?

非常感谢!

1 个答案:

答案 0 :(得分:1)

你错过了构造函数中的参数,为自己分配了引用。变化

public TabsPagerAdapter(FragmentManager fm) {
    super(fm);
    this.activity = activity;
}

public TabsPagerAdapter(FragmentManager fm, FragmentActivity activity) {
    super(fm);
    this.activity = activity;
}

或者你也可以通过FragmentActivity

  public TabsPagerAdapter(FragmentActivity activity) {
        super(activity.getSupportFragmentManager());
        this.activity = activity;
  }

然后将其实例化为TabsPagerAdapter(getSupportFragmentManager(), this)new TabsPagerAdapter(this),具体取决于您选择的那个