9

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?

Jeremy
  • 157
  • 1
  • 8

3 Answers3

15

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));
}
tronman
  • 9,862
  • 10
  • 46
  • 61
JatraTim
  • 608
  • 5
  • 12
6

First of all you don't set "TextView of a Button", because Button extends TextView, you set text of the Button itself. You can try to do this the following way in your activity's onCreate():

//I suppose you create custom ActionBar like this
final View addView = getActivity().getLayoutInflater().inflate(R.layout.my_action_bar, null);
bar.setCustomView(addView);
button=(Button)addView.findViewById(R.id.button);
button.setText("Whatever");

If you use menu items, then you should try this approach:

getSupportMenuInflater().inflate(R.menu.activitymenu, menu);
MenuItem menuItem=menu.findItem(R.id.menuSearch);

Also try looking here,here and here. It should be helpful.

Community
  • 1
  • 1
slezadav
  • 6,104
  • 7
  • 40
  • 61
  • So I don't know if that's working exactly for my situation. I have this actionBar=getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); for the action bar and then some items already in the menu xml. I can't figure out how to access them. – Jeremy Nov 02 '12 at 02:12
1

This code worked for me

actionBar.setCustomView(R.layout.my_action_bar);
button=(Button)actionBar.getCustomView().findViewById(R.id.button);
button.setText("text");