Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change text dynamically for Android Actionbar Button

I have an Action Bar (using actionbarsherlock) that has two items in it. One of them is the amount of points the user has collected in my app. I want to change this Action Bar Button when the amount of points changes.

I can't figure out how to set the TextView of that Button. What can I do to set that via code?

like image 243
Jeremy Avatar asked Nov 01 '12 18:11

Jeremy


People also ask

How can I customize my action bar in Android?

This example demonstrate about how to create a custom action bar in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How do I add action to action bar?

All action buttons and other items available in the action overflow are defined in an XML menu resource. To add actions to the action bar, create a new XML file in your project's res/menu/ directory. The app:showAsAction attribute specifies whether the action should be shown as a button on the app bar.


1 Answers

ActionBar items are from the options menu, rendered as buttons when shown on the bar. If you don't supply an icon, the title of the option MenuItem is used as the title of the button,

So, unless you are using a custom view, and you are simply using a menu item title as the score indicator, you can change that in onPrepareOptionsMenu(). When you need to update, call invalidateOptionsMenu(), and onPrepareOptionsMenu will be called for you.

eg

//user scores some points
mUserScore += points;
invalidateOptionsMenu();

then in the callback:

@Override
public void onPrepareOptionsMenu(Menu menu) {
    MenuItem score = menu.findItem(R.id.score_menu_item);
    score.setTitle(String.valueOf(mUserScore));
}
like image 197
JatraTim Avatar answered Sep 20 '22 02:09

JatraTim