In the previous post, I showed you how to create a basic Options Menu in Android activity. Sometimes, a situation may arise that you need to change the menu item text or icon or anything else depending on a condition. In other words, in order to make the menu items dynamic, we cannot depend on the onCreateOptionsMenu() function.So how can we do it? We will use onPrepareOptionsMenu() method. The onPrepareOptionsMenu() method is always called from within onCreateOptionsMenu() in the actual definition of it in the android.app.activity class.
I’ll be using the source code from my previous post to show you how it’s done. Complete Source code is at the bottom.
- Comment out everything in the onCreateOptionsMenu() method and write the following lines
[java]
super.onCreateOptionsMenu(menu);
return true;
[/java]We are calling the original onCreateOptionsMenu() from the Activity class because that automatically calls the onPrepareOptionsMenu() every time it is called.
- After the onCreateOptionsMenu() write the below code[java]
public boolean onPrepareOptionsMenu(Menu menu){
menu.clear();
int flag = 0;
//int flag = 1;
String temp;
if(flag>0)temp = "MenuItem2on";
else temp = "MenuItem2off";
menu.add(0, 1, 0, "MenuItem1").setIcon(R.drawable.menuitemicon1);
menu.add(0, 2, 0, temp).setIcon(R.drawable.menuitemicon2);
return true;
}
[/java] - Save and run it in the emulator/device.
- You can change it according to your needs to have changing icons or texts. onPrepareOptionsMenu() is a very useful method in such cases.
COMPLETE SOURCE CODE
[java]
package com.nero.myfirstapp;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main, menu);
//menu.add(0, 1, 0, "MenuItem1").setIcon(R.drawable.clock);
//menu.add(0, 2, 0, "MenuItem2").setIcon(R.drawable.checkbox);
super.onCreateOptionsMenu(menu);
return true;
}
public boolean onPrepareOptionsMenu(Menu menu){
menu.clear();
int flag = 0;
//int flag = 1;
String temp;
if(flag>0)temp = "MenuItem2on";
else temp = "MenuItem2off";
menu.add(0, 1, 0, "MenuItem1").setIcon(R.drawable.clock);
menu.add(0, 2, 0, temp).setIcon(R.drawable.checkbox);
return true;
}
}
[/java]