Search code examples
androidpagerslidingtabstrip

Adding Icons instead of text with PagerSlidingTabStrip


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.


Solution

  • 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;
    }