Open the context menu by clicking on the menu item

I am using Android to create an application. I have an activity where I create a options menu, for example below

    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.mymenu, menu);
    return true;
}

The menu is loaded from an XML file:

<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:title="Item1" android:id="@+id/item1" /></menu>

When I click on element 1, I use onOptionsItemSelected in my activity to work after clicking as follows:

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
    case R.id.item1 :
        // here, I would like to open a contextual menu
        return true;
    default :
        return super.onOptionsItemSelected(item);
    }
}

So, when the user clicks on element 1, I would like to open the context menu. Firstly, I don’t know whether it is possible to open the context menu directly without using the hold position on the screen, as shown in several tutorials on the Internet.

If possible, how can I open the context menu in this way?

I thought to use registerForContextMenu()it openContextMenu()in the case of my element 1, but in what representation should I put the parameter?

- , , , .

+3
3

, , Android, . , .

. , , ( , ). , Theme.Dialog manifest.xml:

<activity android:name=".activities.TagPopupActivity"
            android:label="Tagging" android:theme="@android:style/Theme.Dialog">
                ...
</activity>

, . (.. ) , , , , "", - .

+4

, , (, ).

.

+2
private final int OPTION_1 = 21;
private final int OPTION_2 = 22;    

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.mymenu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    ActionMenuItemView btn = findViewById(item.getItemId());

    switch (item.getItemId()) {
        case R.id.action_share:
            PopupMenu popupMenu = new PopupMenu(this, btn);
            popupMenu.getMenu().add(0, OPTION_1, 0, "Option 1");
            popupMenu.getMenu().add(0, OPTION_2, 0, "Option 2");
            popupMenu.setOnMenuItemClickListener(this::onClickMenu);
            popupMenu.show();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

private boolean onClickMenu(MenuItem menuItem) {
    switch (menuItem.getItemId()) {
        case OPTION_1:
            // Clicked option 1
            break;
        case OPTION_2:
            // Clicked option 2
            break;
    }

    return false;
}
0
source

Source: https://habr.com/ru/post/1790196/


All Articles