Öncelikle sepet için bir imageview ve üzerindeki rakam için bir textview oluşturmalısın.
<ImageView android:id="@+id/counterBackground" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/unread_background" /> <TextView android:id="@+id/count" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="1" android:textSize="8sp" android:layout_centerInParent="true" android:textColor="#FFFFFF" />
Daha sonra Java tarafında menu oluşturduğun kod:
@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;
Daha sonra
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); }
Stackoverflowda aynı soru için: https://stackoverflow.com/questions/33729396/how-to-display-count-of-notifications-in-toolbar-icon-in-android