how to make android action bar menu items to click automatically


I had a scenario where I got menu item with name "click" in action bar. I want to make this button auto click with out manually clicking. Is there a way in which I can access android action bar menu item from OnCreateView() and access that particular menu item with name "click" and perform auto click like the way we use for buttons with method "performclick()".
Can anyone help me in sorting out this issue

Upvotes: 4

Views: 6996

Answers (2)

Lalith B
Lalith B

Reputation: 12239

You can create a member variable for the MenuItem and access it when you want. But it may be null so make sure you check for null before accessing it. You could also try using the Actionbar.setCustomView(R.layout.something); and handle the whole layout and actions as your convineance.

protected class fragment extends Fragment{

    MenuItem searchItem;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
      if(searchItem!=null){
        searchItem.setTitle("SEARCH");
        searchItem.setOnMenuItemClickListener(menuItemClickListener);
      }
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
      super.onCreateOptionsMenu(menu, inflater);
      inflater.inflate(com.sample.R.menu.menu_main, menu);
      searchItem = menu.findItem(R.id.search);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      int itemId_ = item.getItemId();
      if (itemId_ == R.id.search) {
        handleYourEvent();
        return true;
      }
      return false;
    }
}

Upvotes: 1

prom85
prom85

Reputation: 17788

you probably use something like following to handle the menu item clicks:

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    if (item.getItemId() == android.R.id.home)
    {
        this.onBackPressed();
    }
}

so just call onOptionsItemSelected(MenuItem item) with the correct menu item... That should do it...

To find the item you want to click, just use something like the following in your menu creation:

private MenuItem mItem = null;

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    getSupportMenuInflater().inflate(R.menu.abs_backup, menu);
    // get a reference to the item you want to click manually
    mItem = menu.findItem(id); 
    return true;
}

and afterwards just call onOptionsItemSelected(mItem); wherever you want...

PS:

it may be more beautiful if you just create a function and call this function in onOptionsItemSelected and wherever you want to simulate the button click... So you don't need a reference to the button and for me, this seems more clean...

Upvotes: 6

Related Questions