Adding Icons instead of text with PagerSlidingTabStrip

1.9k views Asked by At

I am trying to figure out how I can add icons instead of text with the following library - https://github.com/astuetz/PagerSlidingTabStrip

Does anyone know if there is any way to have icons and text? or just have icons instead of the default text.

If you could let me know, that would be highly appreciated.

2

There are 2 answers

4
Rick Sanchez On BEST ANSWER

Implement IconTabProvider interface within you pager adapter. For example :

public class MyPagerAdapter extends FragmentPagerAdapter implements IconTabProvider {  

    private int icons[] = {R.drawable.firstIcon, R.drawable.secondIcon, R.drawable.thirdIcon};


   public MyPagerAdapter (FragmentManager fm) {
      super(fm);
   }

   @Override
   public int getCount() {
      return 3; // number of pages
   }

   @Override
   public Fragment getItem(int position) {
      return MyFragment.newInstance(position);
   }

   @Override
   public int getPageIconResId(int position) {
       return icons[position];
   } 
}

Edit:
To add icons and text, use getPageTitle and return a spannable:

@Override
public CharSequence getPageTitle(int position) {
    // Generate title based on item position
    Drawable image = context.getResources().getDrawable(icons[position]);
    image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
    // Replace blank spaces with image icon
    SpannableString sb = new SpannableString("   " + tabTitles[position]);
    ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
    sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return sb;
}
1
satyapol On

Follow these steps : 1. make your class name as

public class SampleFragmentPagerAdapter extends FragmentPagerAdapter implements
    PagerSlidingTabStrip.IconTabProvider {
  1. Declare drawable

    final int[] icons = new int[]{R.drawable.a, R.drawable.b};

  2. copy paste this function

    @Override public int getPageIconResId(int position) { return icons[position]; }

Thats it. is should work