I'm implementing a SlidingTabLayout in my android application. What my query is that I'd like to implement icons in my Sliding Tabs instead of texts for navigation. I searched heavily on the internet for any such tutorial or sample but found none. I also searched a previous question on stackoverflow: Over Here - SlidingTabLayout with Icons. It was slightly informative but didn't really help me out.
To be clear. I require my tabs to consist of icons only. No text.
As I am new to this whole setup, I'd appreciate if you'd post proper code with an explanation. Thank you for your time and effort!
P.S. I also heard about the pagerslidingtabstrip by Andreaz Stuetz and wondered if that would be more suitable for the type of thing I'm going for...
Also: Here is what I would like my sliding tabs to look like. Check out the top of this image.
EDIT : NOW THAT LOLLIPOP (WITH MATERIAL DESIGN) HAS COME OUT. I HAVE SEEN A LOT OF APPS USING A NEW "ONLY ICON" SLIDING-TAB-LAYOUT
BELOW THEIR TOOLBAR (ANDROID 5.0 ACTION-BAR). IS THEIR ANY NEW WAY TO IMPLEMENT THIS?? THANKS ONCE AGAIN!
The key to this is to return a SpannableString, containing your icon in an ImageSpan, from your PagerAdapter's getPageTitle(position) method:
private int[] imageResId = {
R.drawable.ic_tab_notifications,
R.drawable.ic_tab_weather,
R.drawable.ic_tab_calendar
};
@Override
public CharSequence getPageTitle(int position) {
Drawable image = getResources().getDrawable(imageResId[position]);
image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
SpannableString sb = new SpannableString(" ");
ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return sb;
}
Normally this be would be enough, but the default tab created by SlidingTabLayout makes a call to TextView#setAllCaps(true)
which effectively disables all ImageSpans, so you'll have to use a custom tab view instead:
res/layout/custom_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textStyle="bold"
android:background="?android:selectableItemBackground"
android:padding="16dp"
/>
and where ever you setup/bind to your ViewPager:
SlidingTabLayout slidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
slidingTabLayout.setCustomTabView(R.layout.custom_tab, 0);
slidingTabLayout.setViewPager(viewPager);
(make sure to call setCustomTabView
before setViewPager
)