I want to create a popup menu that appears when I click a button in the options menu. I have been trying a few things but it keeps saying my popup menu is not anchored. Here is the small bit of code I have:

public class MainActivity extends Activity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item){


        View menuItemView = findViewById(R.id.menu_color);
        PopupMenu popupMenu = new PopupMenu(this, menuItemView);
        popupMenu.inflate(R.menu.popup_menu);
        popupMenu.show();
        return true;



}

Main.xml

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

<item
    android:id="@+id/menu_color"
    android:title="@string/menu_color"/>

popup_menu.xml

<item 
    android:id="@+id/item_red"
    android:title="Red"
    android:visible="true"
    android:showAsAction="always"
    />

<item 
    android:id="@+id/item_blue"
    android:title="blue"
    android:visible="true"
    android:showAsAction="always"
    />

<item 
    android:id="@+id/item_green"
    android:title="green"
    android:visible="true"
    android:showAsAction="always"
    />

<item 
    android:id="@+id/item_yellow"
    android:title="yellow"
    android:visible="true"
    android:showAsAction="always"
    />

Related posts

Recent Viewed