How to display count of notifications in toolbar icon in android

后端 未结 4 2104
猫巷女王i
猫巷女王i 2021-02-06 11:05

I would like to make an icon counter for android just like the cart. I have seen many e-commerce app cart icon count increase. I show flipkart app snapshot.:-

4条回答
  •  粉色の甜心
    2021-02-06 11:17

    You can do as follows

    Custom item on my menu - main.xml

    
    
    

    Custom shape drawable (background square) - shape_notification.xml

    
    
        
        
        
    
    

    Layout for my view - feed_update_count.xml

    
    
    

    MainActivity - setting and updating my view

    static Button notifCount;
    static int mNotifCount = 0;    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.main, menu);
    
        View count = menu.findItem(R.id.badge).getActionView();
        notifCount = (Button) count.findViewById(R.id.notif_count);
        notifCount.setText(String.valueOf(mNotifCount));
        return super.onCreateOptionsMenu(menu);
    }
    
    private void setNotifCount(int count){
        mNotifCount = count;
        invalidateOptionsMenu();
    }
    

提交回复
热议问题