Skip to content

Instantly share code, notes, and snippets.

@john-lorrenz
Last active November 7, 2019 05:56
Show Gist options
  • Save john-lorrenz/ae9edb64f0519fd32b2ac53e22b51f6a to your computer and use it in GitHub Desktop.
Save john-lorrenz/ae9edb64f0519fd32b2ac53e22b51f6a to your computer and use it in GitHub Desktop.
Icon Badge Count
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/notifications"
android:orderInCategory="100"
android:title=""
android:icon="<-- your drawable icon here-->"
app:actionLayout="@layout/notification_icon_badge"
app:showAsAction="always" />
</menu>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid android:color="@android:color/holo_red_dark"/>
<stroke android:color="@android:color/white" android:width="1dp"/>
</shape>
// Create action bar item (notification icon)
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.action_bar_notifications, menu)
// Get the menu item
var menuItem = menu.findItem(R.id.notifications)
// Get the view of the menu item
val actionView = menuItem.actionView
// Get the badge inside the action view
var badgeCount = actionView.findViewById(R.id.cart_badge) as TextView
// Manipulate the badge
badgeCount.visibility = View.VISIBLE
badgeCount.text = "12"
// Set on click action
actionView.setOnClickListener {
val intent = Intent(this, HomeNotificationsActivity::class.java)
startActivity(intent)
}
return true
}
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
style="?attr/actionButtonStyle"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clipToPadding="false"
android:focusable="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="<-- your drawable icon here-->"/>
<TextView
android:id="@+id/cart_badge"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_gravity="right|end|top"
android:layout_marginEnd="-5dp"
android:layout_marginRight="-5dp"
android:layout_marginTop="3dp"
android:background="@drawable/badge_background"
android:gravity="center"
android:padding="3dp"
android:textColor="@android:color/white"
android:text="0"
android:textSize="10sp"/>
</FrameLayout>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment