28

The TabLayout class in android provides you with a TabItem that can let you specify a text and a icon. Is it possible to use a custom view as a TabItem?

My tab would look like this

enter image description here

as you can see besides an icon and a text label, I also have a notification symbol (a number inside a yellow circle). how can I make tabs like this?

5 Answers 5

58

In certain cases, instead of the default tab view we may want to apply a custom XML layout for each tab. To achieve this, iterate over all the TabLayout.Tabs after attaching the sliding tabs to the pager:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the ViewPager and set it's PagerAdapter so that it can display items
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        SampleFragmentPagerAdapter pagerAdapter = 
            new SampleFragmentPagerAdapter(getSupportFragmentManager(), MainActivity.this);
        viewPager.setAdapter(pagerAdapter);

        // Give the TabLayout the ViewPager
        TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
        tabLayout.setupWithViewPager(viewPager);

        // Iterate over all tabs and set the custom view
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            tab.setCustomView(pagerAdapter.getTabView(i));
        }
    }

    //...
} 

Next, we add the getTabView(position) method to the SampleFragmentPagerAdapter class:

public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
   private String tabTitles[] = new String[] { "Tab1", "Tab2" };
   private int[] imageResId = { R.drawable.ic_one, R.drawable.ic_two };

    public View getTabView(int position) {
        // Given you have a custom layout in `res/layout/custom_tab.xml` with a TextView and ImageView
        View v = LayoutInflater.from(context).inflate(R.layout.custom_tab, null);
        TextView tv = (TextView) v.findViewById(R.id.textView);
        tv.setText(tabTitles[position]);
        ImageView img = (ImageView) v.findViewById(R.id.imgView);
        img.setImageResource(imageResId[position]);
        return v;
    }

} 

With this you can setup any custom tab content for each page in the adapter.

SOURCE

6
  • of course! can't believe i didnt see the setCustomView in Tablayout.Tab class. Thank you Commented Dec 1, 2016 at 20:16
  • but its not working onTabChange listener, to show selected Tab with highlighted color Commented Jul 20, 2017 at 21:01
  • To change the tab text color you can create a customView and override the setSelected(boolean selected) method to change its own colors accordingly. Commented Apr 5, 2018 at 23:56
  • @Asym is there a way to do this in xml? Commented Jan 23, 2020 at 11:48
  • It wasn't useful because when you use setCustomeView, the highlighted color when you click on item, will be removed. Commented May 30, 2020 at 8:46
5

you can use any layout for each tab item. Firstly add TabItems to TabLayout like that; (my layout has 2 textview and 1 image for each tab)

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toTopOf="parent">

    <com.google.android.material.tabs.TabItem
        android:id="@+id/ti_payroll_tab_tab1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout="@layout/your_custom_layout" />

    <com.google.android.material.tabs.TabItem
        android:id="@+id/ti_payroll_tab_tab2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout="@layout/your_custom_layout" />
</com.google.android.material.tabs.TabLayout>

Then you must find and set views in custom layout.

TabLayout.Tab tab1 = tabLayout.getTabAt(0);

tvTab1Title = tab1.getCustomView().findViewById(R.id.txt_payroll_tab_title);
tvTab1Value = tab1.getCustomView().findViewById(R.id.txt_payroll_tab_value);
ivTab1 = tab1.getCustomView().findViewById(R.id.img_payroll_tab_image);
2
  • How to add this custom tab dynamically? Commented Sep 21, 2020 at 15:59
  • What is the point of using the android:layout attribute if you're going to manually set it up? Commented Oct 27, 2023 at 14:36
3

Documents are very poor on this topic. We can use setCustomView method of tabs to set custom view. Following is a working example:

tab_layout.xml

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="@dimen/tab_height"
    android:background="@color/primary_dark" />

custom_tab_item.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/tab_height"
    android:orientation="horizontal"
    android:padding="@dimen/tab_padding">

    <ImageView
        android:id="@+id/tabIcon"
        android:layout_width="@dimen/tab_icon"
        android:layout_height="@dimen/tab_icon"
        android:layout_centerVertical="true"/>

    <TextView
        android:id="@+id/tabTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@+id/tabIcon"
        android:textColor="@color/white" />

    <TextView
        android:id="@+id/tabSubTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tabTitle"
        android:layout_toEndOf="@+id/tabIcon"
        android:textColor="@color/white" />

</RelativeLayout>

MainActivity.kt

TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position ->
            when (position) {
                0 -> {
                    tab.setCustomView(R.layout.tab_item)
                    tab.customView?.findViewById<ImageView>(R.id.tabIcon)
                        ?.setImageResource(R.drawable.tab1)
                    tab.customView?.findViewById<TextView>(R.id.tabTitle)?.setText(R.string.tab1)
                }
                1 -> {
                    tab.setCustomView(R.layout.tab_item)
                    tab.customView?.findViewById<ImageView>(R.id.tabIcon)
                        ?.setImageResource(R.drawable.tab2)
                    tab.customView?.findViewById<TextView>(R.id.tabTitle)
                        ?.setText(R.string.tab2)
                }
            }
        }.attach()
1

Try to use code below

private View mCustomView;
private ImageView mImageViewCustom;
private TextView mTextViewCustom;
private int count = 0;

public View getCustomTab() {
    mCustomView = LayoutInflater.from(NewHomePageActivity.this).inflate(R.layout.custom_tab, null);
    mImageViewCustom = (ImageView) mCustomView.findViewById(R.id.custom_tab_imageView);
    mTextViewCustom = (TextView) mCustomView.findViewById(R.id.custom_tab_textView_count);
    if (count > 0) {
        mTextViewCustom.setVisibility(View.VISIBLE);
        mTextViewCustom.setText(String.valueOf(count));
    } else {
        mTextViewCustom.setVisibility(View.GONE);
    }
    return mCustomView;
}

private void setupTabIcons() {
    tabLayout.getTabAt(0).setIcon(R.mipmap.ic_home_gray_48);
    tabLayout.getTabAt(1).setIcon(R.mipmap.ic_follow_gray_48);
    tabLayout.getTabAt(2).setIcon(R.mipmap.ic_follower_gray_48);
    tabLayout.getTabAt(3).setIcon(R.mipmap.ic_news_event_gray_48);
    tabLayout.getTabAt(4).setCustomView(getCustomTab());
    tabLayout.getTabAt(5).setIcon(R.mipmap.ic_menu_gray_48);
}

XML

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary">

    <ImageView
        android:id="@+id/custom_tab_imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@mipmap/ic_bell_gray_48"
        android:contentDescription="@string/image_dsc" />

    <TextView
        android:id="@+id/custom_tab_textView_count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_marginEnd="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginBottom="5dp"
        android:background="@drawable/shape_circle"
        android:padding="2dp"
        android:text="1"
        android:textColor="@color/colorWhite"
        android:textSize="11sp" />

</FrameLayout>
1
  • How do you access the views in the customView from the onTabSelected method call to apply a style?
    – saintjab
    Commented Sep 5, 2018 at 15:58
0

I had the same problem - the icon in the tab had been to small and there was no way to make it bigger. I found an alternative of Özer Özcans answer the easiest. The key is the statement android:layout="@layout/your_custom_layout". One can make 3 different custom layouts for 3 different tabs. That way -everything- can be done in xml. To make it easy use a "shared" layout for your first tests. Replicate to custom_layout2,3 and just change the icon drawable names. This offers full control. The only thing that would -not- work is the yellow circle counter in Denny´s question, as this is dynamic. If you need that Özers answer is again the best.

Here are the xml snippets:

<com.google.android.material.tabs.TabLayout
            android:id="@+id/maintab"
            app:layout_constraintTop_toTopOf="parent"
            android:layout_marginTop="0dp"
            android:layout_width="match_parent"
            android:layout_height="65dp"

            app:tabBackground="@drawable/tab_selector">

            <com.google.android.material.tabs.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout="@layout/tab_layout"
               />

            <com.google.android.material.tabs.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout="@layout/tab_layout2"

                />

            <com.google.android.material.tabs.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout="@layout/tab_layout3"
                />
        </com.google.android.material.tabs.TabLayout>

Followed by one of the 3 tab_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="65dp"
android:orientation="horizontal"
>

<ImageView
    android:id="@+id/mytabIcon"
    android:layout_width="100dp"
    android:layout_height="60dp"
    android:scaleX= "0.5"
    android:scaleY= "0.5"
    android:src="@drawable/basis_tab"
    android:layout_centerVertical="true"
    app:tint="@color/whitecream" />

Scaling the image worked nicely with scaleX and Y then. Interestingly the Tablayout class did manage to distribute space equally in 1/3 of screenwidth, and also kept the aspect ratio of the icons. This is excellent since my drawables are big images (so they could explode the layout), while i set a fixed dp width in android:layout_width="100dp". The Tablayout class nicely expands this to the full screen width (which can be variable). Obviously noone wants distorted icons. I also tested what Tablayout does when the width is to small - it then starts to scale down the tab icon.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.