This is a simple post in which I’m going to show you how you can create a simple notification on top of an existing button that looks just like an iOS/OSX notification, as shown below:
I want to do this WITHOUT any 9 patch images whatsoever. If you look closely, you’ll see that the red notification is actually a gradient. The bottom red color is darker than the top. The reason I want to stay away from 9-patch is because its a painful to work with when you need to make changes. The icon you see above is going to be completely implemented in a XML drawable. This will allow it to look great on ldpi, mdpi, hdpi, xhdpi, etc etc etc. After we have the notification icon built (the little red thing) you can lay that on top of anything – in this instance we’re laying it over a button through the use of a FrameLayout.
Building the Shape
The icon is really easy to build actually. Its a simple XML Drawable that is stored in the /res/drawables/ folder:
This XML Drawable creates a rectangle with rounded corners with a corner radius of 10 density pixels. It has a stroke (a border) of 2 density pixels wide and is white in color. The color of the rectangle is a gradient which has a start and end color which are the red and dark red colors in hex. I then add a little padding around the shape so there is room for the content (in this case it will be text, which I’ll show you in one second). Thats pretty much it, you’ve created the shape which will define how the bubble looks.
Laying it out
The code below brings it together. I’ll explain each piece in detail after this code:
Take a look at the LinearLayout above. The LinearLayout has its background set to the XML drawable that you created above. The gravity is set to center so the child views are in the middle. Some padding and margin is added so that little red bubble that we’re creating shows up in the top right corner of the parent view (since, as you can see, we’re using a FrameLayout). This LinearLayout has one child view, a TextView that displays the number and its text color is set to white. Now you just need to place this over a button, which is exactly what the FrameLayout is allowing you to do.
Since the LinearLayout (the red bubble) is at the bottom of the FrameLayout declaration, it is “on top” of everything else. The last item in the FrameLayout XML declaration is what will be on top. Above the LinearLayout you have a Button with a custom background that sets the background to a black/grey gradient. The custom background isn’t covered in this post, but can be downloaded with the sample code for you to play with.
At this point you have a button with a red bubble over it. You can add an android:id attribute to the TextView and update it in your Activity or Fragment code to reflect the proper count number (here I’m just hardcoding it for brevity).
So there you have it, a count bubble that scales across all screen resolutions and looks great.