Tablayout with icons only
One approach is setting the icons after TabLayout.setupWithViewPager() method.
mTabLayout.setupWithViewPager(mViewPager);for (int i = 0; i < mTabLayout.getTabCount(); i++) { mTabLayout.getTabAt(i).setIcon(R.drawable.your_icon);}
The tutorial shown in the following link should cover what you want. https://github.com/codepath/android_guides/wiki/Google-Play-Style-Tabs-using-TabLayout#add-icons-to-tablayout
I copied the relevant section below.
Add Icons to TabLayout
Currently, the TabLayout class does not provide a clean abstraction model that allows for icons in your tab. There are many posted workarounds, one of which is to return a SpannableString, containing your icon in an ImageSpan, from your PagerAdapter's getPageTitle(position) method as shown in the code snippet below:
private int[] imageResId = { R.drawable.ic_one, R.drawable.ic_two, R.drawable.ic_three};// ...@Overridepublic CharSequence getPageTitle(int position) { // Generate title based on item position // return tabTitles[position]; Drawable image = context.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;}
By default, the tab created by TabLayout sets the textAllCaps property to be true, which prevents ImageSpans from being rendered. You can override this behavior by changing the tabTextAppearance property.
<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout"> <item name="tabTextAppearance">@style/MyCustomTextAppearance</item> </style> <style name="MyCustomTextAppearance" parent="TextAppearance.Design.Tab"> <item name="textAllCaps">false</item> </style>
In new version of TabLayout
, google added TabItem
which easily can add Icon through your XML with following code:
<android.support.design.widget.TabLayout app:tabTextColor="@color/gray" app:tabMode="fixed" app:tabBackground="@color/red" app:tabIndicatorHeight="4dp" app:tabIndicatorColor="@color/purple" app:tabPadding="2dp" app:tabSelectedTextColor="@color/white" app:tabMinWidth="64dp" android:layout_height="wrap_content" android:layout_width="match_parent"> <!--add height and width to TabItem --> <android.support.design.widget.TabItem android:text="@string/tab_text"/> <android.support.design.widget.TabItem android:icon="@drawable/ic_android"/> </android.support.design.widget.TabLayout>
See more here.