Context Menu Tutorial

Context Menu work when user press long or long click on the element and then context menu appears. It is also known as floating menu.

Step 1.

Create new application with any name from file menu option.

File → New Project → Application name → select API → Add Blank Activity → Activity Name → finish.

Step 2.

In activity_main.xml layout file design your application.

Add following Controls:-

context menu tutorial

Step 3.

Import Package and write following coding in MainActivity.java class file.

	
    import android.view.View;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
    ListView listView1;
    String contacts[]={"Manzar","Akhtar","Jagjot","Tarun","Susan"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView1=(ListView)findViewById(R.id.listView);
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,contacts);
        listView1.setAdapter(adapter);
        // Register the ListView  for Context menu
        registerForContextMenu(listView1);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
    {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("Select The Action");
        menu.add(0, v.getId(), 0, "Call");//groupId, itemId, order, title
        menu.add(0, v.getId(), 0, "SMS");
    }
    @Override
    public boolean onContextItemSelected(MenuItem item){
        if(item.getTitle()=="Call"){
            Toast.makeText(getApplicationContext(), "calling code", Toast.LENGTH_LONG).show();
        }
        else if(item.getTitle()=="SMS"){
            Toast.makeText(getApplicationContext(),"sending sms code",Toast.LENGTH_LONG).show();
        }else{
            return false;
        }
        return true;
    }
}

Step 4. Final Output

context menu tutorial

Output after long press on the any name.

context menu

Post Your Comment