Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is some example code that worked for me.</p> <p>1: Create a layout for your badge menu item.</p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="48dp" android:layout_height="fill_parent" android:layout_gravity="right" &gt; &lt;!-- Menu Item Image --&gt; &lt;ImageView android:layout_width="48dp" android:layout_height="fill_parent" android:clickable="true" android:src="@drawable/bkg_actionbar_notify_off" /&gt; &lt;!-- Badge Count --&gt; &lt;TextView android:id="@+id/actionbar_notifcation_textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:padding="@dimen/padding_small" android:text="99" android:textColor="@color/holo_orange_dark" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>2: Create a menu item in res/menu and set the actionLayout to your layout</p> <pre><code>&lt;menu xmlns:android="http://schemas.android.com/apk/res/android" &gt; &lt;item android:id="@+id/badge" android:actionLayout="@layout/actionbar_badge_layout" android:icon="@drawable/icn_menu_posts" android:showAsAction="always"&gt; &lt;/item&gt; &lt;/menu&gt; </code></pre> <p>3: Then in onCreateOptionsMenu of your activity or fragment you can do something like this...</p> <pre><code>public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.badge, menu); RelativeLayout badgeLayout = (RelativeLayout) menu.findItem(R.id.badge).getActionView(); TextView tv = (TextView) badgeLayout.findViewById(R.id.actionbar_notifcation_textview); tv.setText("12"); } </code></pre> <p>Note: If you wanted to change the badge count later on, you could store a reference to the Menu object passed to onCreateOptionsMenu and use the same code to get the required view and set a value. </p> <p>=== ApCompat Warning ==================================================</p> <p>If using the AppCompatActivity then you must set the actionView in <code>onCreateOptionsMenu</code></p> <pre><code> @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); MenuItem item = menu.findItem(R.id.badge); MenuItemCompat.setActionView(item, R.layout.actionbar_badge_layout); RelativeLayout notifCount = (RelativeLayout) MenuItemCompat.getActionView(item); TextView tv = (TextView) notifCount.findViewById(R.id.actionbar_notifcation_textview); tv.setText("12"); return super.onCreateOptionsMenu(menu); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload