Friday, September 30, 2011

Context Menu android exam

If you want to associate a context menu to a view on an activity, you need to call the setOnCreateContextMenuListener() method of that particular view. For example, the following code shows how you can associate a context menu with the Button view:
package net.learn2develop.AndroidViews;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.Toast;
 
public class MenuExample extends Activity
{    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);        
        setContentView(R.layout.menu);      
 
        Button btn = (Button) findViewById(R.id.btn1);        
        btn.setOnCreateContextMenuListener(this);
    }
 
    private void CreateMenu(Menu menu)
    {
        //...
    }
 
    private boolean MenuChoice(MenuItem item)
    {        
        //...
    }
 
    //---only created once---
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        super.onCreateOptionsMenu(menu);
        CreateMenu(menu);
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {    
         return MenuChoice(item);    
    }
 
    @Override
    public void onCreateContextMenu(ContextMenu menu, View view, 
    ContextMenuInfo menuInfo) 
    {
         super.onCreateContextMenu(menu, view, menuInfo);
         CreateMenu(menu);
    }
 
    @Override
    public boolean onContextItemSelected(MenuItem item)
    {    
         return MenuChoice(item);    
    }    
 
}