Dynamically change Options Menu Items in Android

Sometimes need to change, add, delete options menu items dynamically after some event or after some situation in application flow.
We all know onCreateOptionsMenu method which helps to create options menu for activity. But in this situation it doesn’t help.
For this situation I use public boolean onPrepareOptionsMenu(Menu menu).

I will show short example which you can copy to your IDE and check my words.
Only one note for this method: don’t forget to clear menu items (menu.clear();) on every method start.
Example:

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

/**
 * Class which shows how to change dynamically options menu items
 * @author FaYnaSoft Labs
 */
public class Main extends Activity {

    private Button clickBtn;
    private boolean isChangedStat = false;
    private static final int MENUITEM = Menu.FIRST;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        clickBtn = (Button) findViewById(R.id.click);
        clickBtn.setText("Click me");
        clickBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (isChangedStat) {
                    isChangedStat = false;
                } else {
                    isChangedStat = true;
                }
            }
        });
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.clear();
        if (isChangedStat) {
            menu.add(0, MENUITEM, 0, "True");
        } else {
            menu.add(0, MENUITEM, 0, "False");
        }
        return super.onPrepareOptionsMenu(menu);
    }
}

In this example I change after button click text in options menu item. It is very simple example. You can modify it for your problem. For example add, delete options menu items.

Why I recommended to clear menu? If you will not clear menu then after every click you will have plus one menu item.

Try to comment and you will see what I mean.

Hope this article was useful for you.
Don’t forget to grab our RSS feeds.

Share

2 comments to Dynamically change Options Menu Items in Android

Leave a Reply

  

  

  

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

A sample text widget

Etiam pulvinar consectetur dolor sed malesuada. Ut convallis euismod dolor nec pretium. Nunc ut tristique massa.

Nam sodales mi vitae dolor ullamcorper et vulputate enim accumsan. Morbi orci magna, tincidunt vitae molestie nec, molestie at mi. Nulla nulla lorem, suscipit in posuere in, interdum non magna.