Adding badge to tab in android

后端 未结 5 1689
生来不讨喜
生来不讨喜 2021-02-04 21:38

i want to add badge to tab in my app as in iPhone.

Screen shot of badge used in iPhone is in the following link:

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-04 22:41

    After tweaking around with a few other solutions I came up with something simple and hope this would help someone.

    create a custom tab layout tab_badge.xml

    
    
    
    
    
    
    
    
    

    badge_background.xml is an oval drawable filled with the color you want for the badge

    
    
    
    
    

    Extend textview to get myBadgeView class:

    public class myBadgeView extends TextView {
    
    private View target;
    
    public myBadgeView(Context context, View target) {
        super(context);
        init(context, target);
    }
    
    private void init(Context context, View target) {
        this.target = target;
    }
    
    public void updateTabBadge(int badgeNumber) {
        if (badgeNumber > 0) {
            target.setVisibility(View.VISIBLE);
            ((TextView) target).setText(Integer.toString(badgeNumber));
        }
        else {
            target.setVisibility(View.GONE);
        }
    }
    }
    

    In your activity declare the tablayout as follows:

    tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    TabLayout.Tab tab1 = tabLayout.newTab();
        tab1.setCustomView(R.layout.tab_badge);
        TextView tab_text_1 = (TextView) tab1.getCustomView().findViewById(R.id.tab_text);
        tab_text_1.setText("Tab1");
        tabLayout.addTab(tab1);
        badge1 = new myBadgeView(this, tab1.getCustomView().findViewById(R.id.tab_badge)); tab1.getCustomView().findViewById(R.id.tab_badge);
    
     //set the badge for the tab
        badge1.updateTabBadge(badge_value_1);
    

提交回复
热议问题