I am learning to use ViewPager and PagerTabStrip to implement navigation bar. I have implemented it, my problem is: every time I open the app fresh, the titles don't show, but after I swipe it once, the titles all appear again, and then everything is normal. code shown below:
Customised Adapter
public class MyPagerAdapter extends PagerAdapter {
private List<View> viewList;
private List<String> titleList;
public MyPagerAdapter(List<View> viewList, List<String> titleList){
this.viewList = viewList;
this.titleList = titleList;
}
@Override
public int getCount() {
return viewList.size();
}
@Override
public boolean isViewFromObject(View view, Object o) {
return view == o;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(viewList.get(position));
return viewList.get(position);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(viewList.get(position));
}
@Override
public CharSequence getPageTitle(int position) {
return titleList.get(position);
}
}
.xml File:
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
<android.support.v4.view.PagerTabStrip
android:id="@+id/tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
/>
</android.support.v4.view.ViewPager>
This is the screenshot of "Just clicked the app icon":
And this is after I swiped to the second page:
I'm really frustrated. Thanks!!
Instead of using android.support.v4.view.PagerTabStrip , use android.support.design.widget.TabLayout for displaying tabs for viewPager. It is included in Google Design Support Library.
See this link for more information http://android-developers.blogspot.in/2015/05/android-design-support-library.html
Just few lines:
viewPager=(ViewPager)v.findViewById(R.id.viewPager);
ViewPagerAdapter adapter=new ViewPagerAdapter(this.getChildFragmentManager(),doctor);
adapter.setViewPagerFragmentListener(this);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager); //Sync Tabs with viewPager
tabLayout.setTabsFromPagerAdapter(adapter); //Setup tabs titles
And to change the titles use the following code in ViewPagerAdapter
@Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Title 1";
case 1:
return "Title 2";
case 2:
return "Title 3";
}
return super.getPageTitle(position);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With