Quick Tip: Android Add Image to PagerTabStrip or PagerTitleStrip

If you’ve ever wanted to place images instead of text in the PagerTabStrip or PagerTitleStrip or even a combination of text and image, then that is surely possible. Here’s how your getPageTitle() method in the pager adapter implementation should look like:

@Override
public CharSequence getPageTitle(int position) {

    SpannableStringBuilder sb = new SpannableStringBuilder(" Page " + (position + 1)); // space added before text for convenience

    Drawable drawable = mContext.getResources().getDrawable( R.drawable.ic_launcher );
    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
    ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
    sb.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    return sb;
}

This method will prepend the text (like ” Page 1″ – notice the space prefix) with res/drawable/ic_launcher.png in the tabs.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

Reference: http://stackoverflow.com/a/12837635

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.

2 thoughts on “Quick Tip: Android Add Image to PagerTabStrip or PagerTitleStrip”

Leave a Reply

Your email address will not be published. Required fields are marked *