How to show Notification Counter in a Tablayout?

5.4k views Asked by At

I saw this stack overflow post but it didn't help me understand what I had to do. I understand the concept of how I am going to increment the counter's value from my query.

But I don't understand what I should use. Should I use Notification notification; or BadgeViewer badgeViewer;? I would prefer a way where I don't have to import a library.

2

There are 2 answers

2
Karakuri On BEST ANSWER

Make a layout resource for your tabs. It should include something that represents your "badge" (a simple TextView will work if you just want to show a number). When you create the tabs, specify this custom layout.

private TabLayout tabLayout;

// in onCreate()
tabLayout = (TabLayout) findViewById(R.id.tabs);
for (int i = 0; i < NUM_TABS; i++) {
    TabLayout.Tab tab = tabLayout.newTab()
            .setText("tab name")
            .setCustomView(R.layout.custom_tab);
    tabLayout.addTab(tab);
}

Note that for setText() to work properly, your layout needs a TextView with android:id="@android:id/text1" (this is not the badge text, this is the tab name).

When you want to update the badge for a tab, you can get the Tab and ask for its view, find the badge, and set its text.

TabLayout.Tab tab = tabLayout.getTabAt(3); // fourth tab
View tabView = tab.getCustomView();
TextView badgeText = (TextView) tabView.findViewById(R.id.badge_text);
badgeText.setText(...);
0
Kamran Khadim On

user material design instead of apcompact design and here is the one line code to add badge to tab like whatsapp

  tabLayout.getTabAt(0).getOrCreateBadge().setNumber(3);//tab#1

so this will add badge to the tab you wanted

to remove the badge on tab selected

            viewPager.addOnPageChangeListener(
            new ViewPager.OnPageChangeListener() {

                @Override
                public void onPageScrolled(
                        int position, float positionOffset, int positionOffsetPixels) {}

                @Override
                public void onPageSelected(int position) {

              

                    if (position == 0) {
                        tabLayout.getTabAt(0).removeBadge();
                    }
                    if (position == 2) {
                   

                        
                        tabLayout.getTabAt(2 ).removeBadge();
                    }
                }

                @Override
                public void onPageScrollStateChanged(int state) {}
            });