使用 getPageTitle() 的空对象引用
Null Object reference with getPageTitle()
我需要在我的 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]);
}
}
使用此代码会使应用程序崩溃。我该如何解决这个问题?
非常感谢!
您错过了构造函数中的参数将引用分配给自身。变化
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)
一样实例化它,具体取决于您选择的那个
我需要在我的 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]);
}
}
使用此代码会使应用程序崩溃。我该如何解决这个问题?
非常感谢!
您错过了构造函数中的参数将引用分配给自身。变化
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)
一样实例化它,具体取决于您选择的那个