Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a onMenuItemClickListener in android

Tags:

android

How do I implement an onMenuItemClickListener?

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    getMenuInflater().inflate(R.menu.gameoptions, menu);
    menu.findItem(R.id.menu_item).setIntent(new Intent(this, QMenuActivity.class));
    menu.findItem(R.id.back_item).setOnMenuItemClickListener;
    return true;
}

I want the back_item once clicked on to call a function within the page, how do I do it?

like image 220
Beginner Avatar asked Jan 14 '11 13:01

Beginner


2 Answers

I'm assuming you want to access a non-static function in your activity. Without too much information from you, try something like what's below:

    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuItem item = menu.findItem(R.id.back_item);
    item.setOnMenuItemClickListener(new OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {
            YourActivity.this.someFunctionInYourActivity();
            return true;
        }
    });
    return true;
}
like image 82
Matt Avatar answered Sep 21 '22 00:09

Matt


Here is the way I do it if I am going to inflate an xml menu.

I first inflate the menu when it is called:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.test, menu);
    return true;
}

Then wait for a press and check which ID was pressed:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.item1:
            ... code ...
            return true;
        case R.id.item2:
            ... code ...
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

Hope this helps!

like image 40
DanO Avatar answered Sep 21 '22 00:09

DanO