How to display count of notifications in toolbar icon in android

后端 未结 4 2175
猫巷女王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:26

    In my solution, whenever a new notification arrives, the counter will increase (as observed in shopping apps)

    Try this, it works on my MOTO e2.

    Make sure your API Level > 14

    Create a layout like:

    
        
    
        
    
    

    In onCreateOptionMenu,

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
       getMenuInflater().inflate(R.menu.menu_main, menu);
    
       MenuItem menuItem = menu.findItem(R.id.testAction);
       menuItem.setIcon(buildCounterDrawable(count,  R.drawable.ic_menu_gallery));
    
       return true;
    }
    

    Now, build method for Icon :

    private Drawable buildCounterDrawable(int count, int backgroundImageId) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.counter_menuitem_layout, null);
        view.setBackgroundResource(backgroundImageId);
    
        if (count == 0) {
            View counterTextPanel = view.findViewById(R.id.counterValuePanel);
            counterTextPanel.setVisibility(View.GONE);
        } else {
            TextView textView = (TextView) view.findViewById(R.id.count);
            textView.setText("" + count);
        }
    
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
    
        view.setDrawingCacheEnabled(true);
        view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);
    
        return new BitmapDrawable(getResources(), bitmap);
    }
    

    You can refer from here

提交回复
热议问题