Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 903
Android_programmer_office Avatar asked Mar 22 '23 02:03

Android_programmer_office


1 Answers

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...

like image 164
prom85 Avatar answered Apr 28 '23 02:04

prom85