I am working with the FragmentPagerAdapter and have a problem with the getPageTitle() method. Everythings is working but it. plz take a look at my code blowing and help me out.
public class MyFragmentPageAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
public final static String PAGE_CURRENT = "current_age";
public final static String PAGE_ID = "id";
int id = 0;
public MyFragmentPageAdapter(FragmentManager fm, int id) {
super(fm);
this.id = id;
}
@Override
public Fragment getItem(int position) {
MyFragment myFragment = new MyFragment();
Bundle bundle = new Bundle();
bundle.putInt(PAGE_CURRENT, position + 1);
bundle.putInt(PAGE_ID, id);
myFragment.setArguments(bundle);
return myFragment;
}
@Override
public CharSequence getPageTitle(int position) {
CharSequence title = null;
if (position == 0) {
title = "a";
} else if (position == 1) {
title = "b";
} else if (position == 2) {
title = "c";
}
return title;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return PAGE_COUNT;
}
}
And in my main Activity i declared:
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setOnPageChangeListener(this);
FragmentManager fm = getSupportFragmentManager();
MyFragmentPageAdapter fragmentAdapter = new MyFragmentPageAdapter(fm,
id);
pager.setAdapter(fragmentAdapter);
// try the below code
public class MyFragmentPageAdapter extends FragmentPagerAdapter {
protected static final String[] CONTENT = new String[] { "a", "b", "c"};
final int PAGE_COUNT = 3;
public final static String PAGE_CURRENT = "current_age";
public final static String PAGE_ID = "id";
int id = 0;
private int mCount = CONTENT.length;
// CHANGE STARTS HERE
private int current_position=0;
public void set_current_position(int i) {
current_position = i;
}
public MyFragmentPageAdapter(FragmentManager fm, int id) {
super(fm);
this.id = id;
}
@Override
public Fragment getItem(int position) {
MyFragment myFragment = new MyFragm`enter code here`ent();
Bundle bundle = new Bundle();
bundle.putInt(PAGE_CURRENT, position + 1);
bundle.putInt(PAGE_ID, id);
myFragment.setArguments(bundle);
return myFragment;
}
@Override
public CharSequence getPageTitle(int position) {
if (position == current_position-1) {
return "Previous";
} else if (position == current_position+1) {
return "Next";
}
// CHANGE ENDS HERE
return MyFragmentPageAdapter.CONTENT[position % CONTENT.length];
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return PAGE_COUNT;
}
}
I had the same problem and assume it's an Android bug. Set the page title in TabLayout.createTabAtPosition(), with this code: return newTab().setText("the page title");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.