我正在测试 FragmentPagerAdapter 并且我之前在一个类中拥有它。一切正常,但是一旦我分离 SectionsPagerAdapter 类,getString 在 getPageTitle 函数下不起作用。
我知道 getPageTitle 是 PagerAdapter 类的一部分,但我想知道在这个类中包含该函数的最佳方法是什么。我需要扩展课程吗?
SectionsPageAdapter 类
import java.util.Locale;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
// A FragmentPagerAdapter that returns a fragment corresponding to one of the sections/tabs/pages.
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.myFriendsTab).toUpperCase(l);
case 1:
return getString(R.string.myDealsTab).toUpperCase(l);
case 2:
return getString(R.string.featuredDealsTab).toUpperCase(l);
case 3:
return getString(R.string.browseCategoriesTab).toUpperCase(l);
case 4:
return getString(R.string.localDealsTab).toUpperCase(l);
}
return null;
}
@Override
public int getCount() {
// Show 5 total pages.
return 5;
}
}
MainActivity 类
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
// Fragment PagerAdapter keeps every loaded fragment in memory.
// If too memory intensive, switch to FragmentStatePagerAdapter.
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager; // ViewPager that will host section contents.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creates the adapter that will return a fragment for each of the primary sections.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), null);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}