View

Wednesday 17 August 2011

How to create contextmenu in android

creating a context menu is very simple,Here i use Textview name as press me on long,when the textview is pressed for long,its open a context menu.In that context menu i use New,edit,copy,paste and delete.
Inside of the onCreate Method,we have to registerForcontextmenu(controls name)
Example: press=(TextView)findViewById(R.id.press_tv);
               registerForContextMenu(press); 
Then we  need to override the onCreateContextMenu method to create the menu:
 @Override 
   public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {  
  super.onCreateContextMenu(menu, v, menuInfo);  
   menu.setHeaderTitle("Context Menu");  
   menu.add(0, v.getId(), 0, "New");  
   menu.add(0, v.getId(), 0, "Edit");  
   menu.add(0, v.getId(), 0, "copy");  
   menu.add(0, v.getId(), 0, "Paste");  
   menu.add(0, v.getId(), 0, "Delete");  
when the item is selected,that items action can perform here,using onContextItemSelected method.
Here i use function for only "New" just passing the Intent,If u want some functions mean, you write a else if () and perform some more actions there.
 @Override 
  public boolean onContextItemSelected(MenuItem item) {  
   if(item.getTitle()=="New"){
    Intent np=new Intent(getApplicationContext(),NewPage.class);
    startActivity(np);
    function1(item.getItemId());}  
   else if(item.getTitle()=="Save"){
    //Some funtion perform here//
    function2(item.getItemId());}  
    else {return false;}  
  return true;  
 }
create a method for function1.... function n,
private void function2(int itemId) {
  // TODO Auto-generated method stub
 
 }
 private void function1(int itemId) {
  // TODO Auto-generated method stub
 
 } 
Result is:
           

pic1

pic2

 
  

pic3

pic4
Download full source code 

5 comments: