Dynamic Menu in Android

[code lang=”java”]
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MenuDemo extends Activity {
/** Called when the activity is first created. */
private Context context;
Button btnMenu;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
LinearLayout llay = new LinearLayout(context);
btnMenu = new Button(context);
btnMenu.setText(“Show Menu”);
llay.addView(btnMenu);
setContentView(llay);
registerForContextMenu(btnMenu);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {//Context Menu that appears when long clicked.
Menu m_menu = menu;
m_menu.add(Menu.NONE, Menu.FIRST+1, 0, “Settings”);
m_menu.add(Menu.NONE, Menu.FIRST+2, 0, “About”);
m_menu.add(Menu.NONE, Menu.FIRST+3, 0, “Exit”);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//Menu that appears when menu button is pressed on device
Menu m_menu = menu;
m_menu.add(Menu.NONE, Menu.FIRST+3, 0, “Settings”);
m_menu.add(Menu.NONE, Menu.FIRST+4, 0, “About”);
m_menu.add(Menu.NONE, Menu.FIRST+5, 0, “Exit”);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
String msg=”Selected from menu: “;
switch (item.getItemId()){
case Menu.FIRST+3:
Toast.makeText(this, msg+”Settings Menu”, Toast.LENGTH_LONG).show();
return true;
case Menu.FIRST+4:
Toast.makeText(this, msg+”About Menu”, Toast.LENGTH_LONG).show();
return true;
case Menu.FIRST+5:
Toast.makeText(this, msg+”Exit Menu”, Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
String msg=”Selected from context menu: “;
switch (item.getItemId()){
case Menu.FIRST+1:
Toast.makeText(this, msg+”Settings”, Toast.LENGTH_LONG).show();
return true;
case Menu.FIRST+2:
Toast.makeText(this, msg+”About”, Toast.LENGTH_LONG).show();
return true;
case Menu.FIRST+3:
Toast.makeText(this, msg+”Exit”, Toast.LENGTH_LONG).show();
return true;
}
return super.onContextItemSelected(item);
}
}

About the author

Janaki(http://mjanaki.com) - A Software developer with 9+ years of experience in multiple technology projects across web, mobile, and cloud applications with expertise in PHP, C#, MySQL, Web services and open source platforms.

Similar Posts

Leave a reply

required*

Eye Test: * Time limit is exhausted. Please reload CAPTCHA.