How to add badges on Toolbar MenuItem Icons

后端 未结 2 969
天命终不由人
天命终不由人 2021-01-31 11:17

I tried to find an answer for myself but couldn\'t find it.

I need make badge on the MenuItem icon in the Toolbar, like this:

How can I make this?

2条回答
  •  一生所求
    2021-01-31 11:59

    Here is step by step functionality:

    add menu.xml

        
        
    
             
        
    

    Then add notification_layout.xml, this layout will be used as the notification icons layout

         
        
    
         
    
         
        
    

    now inside Activity

     @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
    
        final View notificaitons = menu.findItem(R.id.actionNotifications).getActionView();
    
        txtViewCount = (TextView) notificaitons.findViewById(R.id.txtCount);
        updateHotCount(count++);
        txtViewCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateHotCount(count++);
            }
        });
        notificaitons.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
        //    TODO
            }
        });
    
    
        return true;
    }
    

    You can put following function (taken from stackoverflow) inside the activity to update counter:

        public void updateHotCount(final int new_hot_number) {
        count = new_hot_number;
        if (count < 0) return;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (count == 0)
                    txtViewCount.setVisibility(View.GONE);
                else {
                    txtViewCount.setVisibility(View.VISIBLE);
                    txtViewCount.setText(Integer.toString(count));
                    // supportInvalidateOptionsMenu();
                }
            }
        });
    }      
    

提交回复
热议问题