user3486440
user3486440

Reputation: 357

How to create a floating context menu?

I would like to open a menu when I click on a button. I tried to create a floating context menu, but when I press button nothing happens.

MainActivity.java

public class MainActivity extends ListActivity {

    private Button button1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button1 = (Button)findViewById(R.id.button1);

        registerForContextMenu(button1);
    }

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

    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.item1:
                function();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.prounitconverter.prounitconverter.MainActivity" >

    <item android:id="@+id/item1"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />
</menu>

Also, how can I create two menus, for two different buttons?

Upvotes: 2

Views: 1115

Answers (2)

Jin35
Jin35

Reputation: 8612

If you are looking for simple dropdown menu - use PopupMenu:

//anchorView - any view, where you want show menu
PopupMenu popupMenu = new PopupMenu(anchorView.getContext(), anchorView);
popupMenu.inflate(R.menu.my_menu_xml);
popupMenu.show();

Upvotes: 1

Technivorous
Technivorous

Reputation: 1712

for two different menus make two different xml files and name them different then just inflate them by name.... code to follow.

as for the button, you have no onclick method

this needs to be in onCreate, after you init the button

this.button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            //open your menu here
            }
        });

this.button2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //open your menu here } });

Upvotes: 0

Related Questions