我正在为Toolbar
中的图标添加徽章。我使用onCreateOptionMenu
来扩充工具栏中的图标。我需要在按钮上单击使用“菜单”以使用LayerDrawable
为徽标添加徽章。我发现您可以访问this之类的菜单。但是,当我像这样使用菜单时,图标不会更新,它会再次重新创建,以便有2个图标。一个有另一个没有的徽章。如果我再次单击该按钮,则会显示3个图标。有没有办法正确地做到这一点?
public class ProdDetailsActivity extends AppCompatActivity {
private SQLiteHandler db;
private MenuItem itemCart;
private Menu menu;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_proddetails);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public void addcart(View view){
updatecart();
}
public void updatecart(){
//Getting current count frm database
HashMap<String, String> pro = db.getCartCount();
String count = pro.get("cartc");
if(TextUtils.isEmpty(count)) {
getMenuInflater().inflate(R.menu.cart_menu, menu);
MenuItem itemCart = menu.findItem(action_cart);
LayerDrawable icon = (LayerDrawable) itemCart.getIcon();
setBadgeCount(ProdDetailsActivity.this, icon, "1");
db.addCart("1");
} else {
int cc = Integer.parseInt(count);
String finalcount = String.valueOf(cc+1);
Log.e("sammy_finalcount ",finalcount);
getMenuInflater().inflate(R.menu.cart_menu, menu);
MenuItem itemCart = menu.findItem(action_cart);
LayerDrawable icon = (LayerDrawable) itemCart.getIcon();
setBadgeCount(ProdDetailsActivity.this, icon, finalcount);
db.addCart(finalcount);
}
}
public void setBadgeCount(Context context, LayerDrawable icon, String count) {
Log.e("sammy_count ",count);
BadgeDrawable badge;
Drawable reuse = icon.findDrawableByLayerId(R.id.ic_badge);
if (reuse != null && reuse instanceof BadgeDrawable) {
badge = (BadgeDrawable) reuse;
} else {
badge = new BadgeDrawable(context);
}
badge.setCount(count);
icon.mutate();
icon.setDrawableByLayerId(R.id.ic_badge, badge);
}
@Override
protected void onResume() {
super.onResume();
updatecart();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.clear();
//Accessing Menu here
this.menu=menu;
getMenuInflater().inflate(R.menu.cart_menu, menu);
MenuItem itemCart = menu.findItem(action_cart);
LayerDrawable icon = (LayerDrawable) itemCart.getIcon();
setBadgeCount(this,icon, "0");
return super.onCreateOptionsMenu(menu);
}
}