2

I have an ActionBarSherlock with one menu item in my bar. When I'm call View item = findViewById(R.id.my_item);in activity's button onClick all works fine as expected. But when I try to do this in onCreate or onResume or even in onPostResume it is always null. I also tryed do this in onCreateOptionsMenu(Menu menu) after inflating my menu from resource, but without any succes.

Therefore I can't understand when actionbar items created and how to catch this moment?

Dmitriy Tarasov
  • 1,949
  • 20
  • 37

3 Answers3

2

As it has been said here and here, getActionView returns the view that we sets in setActionView. Therefore, the only one way to customize action bar menu item described here

Community
  • 1
  • 1
Dmitriy Tarasov
  • 1,949
  • 20
  • 37
1

actually it is possible to get the view of the action item, even if it's not customized.

however, do note that sometimes action items get to be inside the overflow menu so you might get a null instead.

so, how can you do it?

here's a sample code:

public boolean onCreateOptionsMenu(final Menu menu) {
  getSupportMenuInflater().inflate(R.menu.main, menu);
  new Handler().post(new Runnable() {
    @Override
    public void run() {
      final View syncItemView = findViewById(R.id.action_search);
      ...

this was tested when using actionBarSherlock library, on android 4.1.2 and android 2.3.5 .

another alternative is to use a more extensive way , used on the showcaseView library, here .

android developer
  • 114,585
  • 152
  • 739
  • 1,270
  • 1
    @SteelFedeX Sadly that's how Github works . You need to find the ShowcaseView class there. I've updated the link again. Hope it works now. – android developer Jan 29 '16 at 07:29
0

first of all get a menu reference as below:

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
     getMenuInflater().inflate(R.menu.custom_menu, menu);
     customMenu = menu;
     return super.onCreateOptionsMenu(menu);
 }

after that you can get the item you need as below

     customMenu.getItem(0);
Moaz H
  • 776
  • 1
  • 6
  • 5