将长按添加到动态生成的菜单项

时间:2018-08-07 06:13:59

标签: android

好的,所以我有一个动态菜单(在我的导航抽屉中),它是这样生成的:

在我的Main.java onCreate()中:

DatabaseManager databaseAccess = DatabaseManager.getInstance(this);
databaseAccess.open();
List<String> folders = databaseAccess.getFolders();
databaseAccess.close();

// Set up the menu items
setupMenu(folders);

这会将标题放入名为“ folders”的数组中,然后运行setupMenu函数:

private void setupMenu(List<String> folders) {
    // Sets up the menu
    Log.i("Folder Size",String.valueOf(folders.size()));
    NavigationView navView = findViewById(R.id.nav_view);
    Menu menu = navView.getMenu();
    int x = 0;
    while(x < folders.size()) {
        menu.add(R.id.myfolders,Menu.NONE,Menu.NONE,folders.get(x++));
    }
    navView.invalidate();
}

将其添加到id:myfolders中的activity_main_drawer

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="navigation_view">

    <item android:title="My Folders"
        android:orderInCategory="1"
        android:id="@+id/myfolders">
        <menu></menu>
    </item>

    <item android:checkableBehavior="single" android:orderInCategory="2">
        <menu android:id="@+id/about_menu">
            <item  android:id="@+id/system_about"
                    android:title="About"
                    android:icon="@drawable/ic_info" />
            </menu>
    </item>
</menu>

这一切都很好,但是我想在菜单项中添加longpress功能。我不知道该怎么做,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您从MenuItem获得了menu.add(),然后可以致电:

menuItem.getActionView().setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        return false; // true
    }
});

但在设置操作视图之前menuItem.setActionView(new ImageButton(this))