A different MenuContextual for each ImageButton

1

How can I have a different context menu for different ImageButtons? For example, to be concrete:

  

Image 1 - Contextual Menu 1

     

Image 2 - Contextual Menu 2

     

...

This is what I do to have a contextual menu in an ImageButton:

    registerForContextMenu(icon_cat_accesorios);

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

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.prueba1_menu:
                    Intent abc = new Intent(getApplicationContext(), prueba.class);
                    startActivity(abc);
                    return true;
                case R.id.prueba2_menu:
                    Intent def = new Intent(getApplicationContext(), prueba.class);
                    startActivity(def);
                    return true;
                default:
                    return super.onOptionsItemSelected(item);

            }
        }
    
asked by UserNameYo 27.01.2017 в 23:58
source

1 answer

3

In this case you can create another menu (.xml) which would be open according to the button you assign.

Both buttons must be registered to open the context menu.

registerForContextMenu(imageButtonA);
registerForContextMenu(imageButtonB);

When you open the context menu (by means of onCreateContextMenu() ) you determine the id of the button (view) and the menu that the button will open.

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
    super.onCreateContextMenu(menu, v, menuInfo);

    MenuInflater inflater = getMenuInflater();
    if(v.getId() == R.id.ImageButtonA) { //Boton A abre menú definido en menu.xml
        inflater.inflate(R.menu.menu, menu);
    }
    if(v.getId() == R.id.ImageButtonB) {
        inflater.inflate(R.menu.menu2, menu); //Boton B abre menú definido en menu2.xml
    }
}

Now to determine what we will open from the menu option we do it within onContextItemSelected()

public boolean onContextItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.prueba1_menu:
            Intent abc = new Intent(getApplicationContext(), SecondActivity.class);
            startActivity(abc);
            return true;
        case R.id.prueba2_menu:
             Intent def = new Intent(getApplicationContext(), prueba.class);
             startActivity(def);
             return true;
        default:
            return super.onOptionsItemSelected(item);

    }
}
    
answered by 28.01.2017 / 00:10
source