Search code examples
androidandroid-layoutandroid-tablayout

Can a custom view be used as a TabItem?


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?


Solution

  • 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