Search code examples
javaandroidandroid-tablayoutbadge

How to show Notification Counter in a Tablayout?


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.


Solution

  • 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(...);