从操作栏项目显示弹出菜单

时间:2019-01-29 07:33:24

标签: java android popup popupmenu androidx

因此,我试图将PopupMenu添加到对列表进行排序的ActionBar项目中。我在stackoverflow中看到了一些答案,但是没有一个对我有用。下面是代码。

XML

菜单项:

<item
    android:id="@+id/sortByBackers"
    android:icon="@drawable/ic_sort"
    android:title="Sort By Backers"
    app:showAsAction="always" />

PopupMenu:

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

活动

 public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.bar_menu, menu);
   //...
   //...
    MenuItem sortItem = menu.findItem(R.id.sortByBackers);

    sortItem.setOnMenuItemClickListener(item -> {
        View view = findViewById(R.id.default_list);
        popupMenu = new PopupMenu(getApplicationContext(), view);

        popupMenu.inflate(R.menu.sort_or_default);
        popupMenu.setOnMenuItemClickListener(item1 -> {
            switch (item1.getItemId()) {
                case R.id.default_list:
                    kickstarterAdapter.setData(kickstartersList);
                    break;
                case R.id.sort:
                    kickstarterAdapter.sortList();
                    break;
                default:
                    kickstarterAdapter.sortList();
            }
            popupMenu.show();
            return true;
        });
        return true;
    });

`

0 个答案:

没有答案