Mohammad Mohammad - 1 year ago 99
Android Question

Opening a floating menu (context menu) in Android?

I created a new menu, named drmenu.xml. It works correctly when i press menu button, but I need to open a context menu when the user press the button.
The below code the button just show a toast.

this is my xml layout:

android:gravity="right|center_vertical" >
android:src="@drawable/imageiew6" />

and this is my java code:

final LinearLayout callback_var = (LinearLayout) findViewById(;
callback_var.setOnClickListener(new android.view.View.OnClickListener() {

public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "this is repeated", Toast.LENGTH_LONG).show();

Answer Source

If you want create a context Menu, you have to call the method registerForContextMenu() passing it the View that should be associated with the context menu.

For example, supposing to associate the context menu with a Button:

Button button = (Button) findViewById(;

which can be called in the onCreate() of your Activity. Then, inside the same activity, you need to override the onCreateContextMenu() method.

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(, menu);

Then you have to implement onContextItemSelected(), for triggering the proper action when a item inside the context menu is pressed:

public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
            // your first action code
            return true;
            // your second action code
            return true;
            return super.onContextItemSelected(item);

And you are done, now the long press click on the button opens a the context menu you defined in the the your_context_menu.xml file.

Consider that opening the context menu with a long press is complain with the Android standard UI, however If you want that your context menu appear on a simple tap you can look here the answer

NOTE: As said here

An ID need not be unique throughout the entire tree, but it should be unique within the part of the tree you are searching (which may often be the entire tree, so it's best to be completely unique when possible).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download