动态上下文菜单选项

And*_*yuk 1 android

是否可以在Android中创建动态上下文菜单?

我的意思是,例如,如果我有一个项目列表,可以处于两种状态:"读取"和"未读".我希望能够显示一个上下文菜单,其中包含未读项目的"标记为已读"选项,以及读取项目的"标记为未读".

所以点击:

> read
> unread <-- click
> read 
Run Code Online (Sandbox Code Playgroud)

将显示上下文菜单"标记为已读",结果为:

> read
> read
> read   <-- click
Run Code Online (Sandbox Code Playgroud)

将显示菜单"标记为未读".

是否有一些功能允许我在显示之前自定义上下文菜单的创建?

欢迎任何帮助!

Cri*_*ian 5

由于您不提供代码,这是基本方法:

@Override
public void onCreateContextMenu(ContextMenu contextMenu,
                                View v,
                                ContextMenu.ContextMenuInfo menuInfo) {
    AdapterView.AdapterContextMenuInfo info =
            (AdapterView.AdapterContextMenuInfo) menuInfo;

    String actionString = "Mark as Read";

    // if it's alredy read
    if ( ((TextView) info.targetView).getText().toString().equals("read") )
        actionString = "Mark as Unread";

    menu.setHeaderTitle("Action");
    menu.add(0, 0, 0, actionString);
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我假设列表中填充了TextViews,其中可以包含字符串"read"或"unread".正如我已经说过的,这是一种非常基本的方法.这里重要的是要注意ContextMenu.ContextMenuInfo对象的使用方式.

此外,要读取所选项目的状态,您可以使用item.getMenuInfo()方法内部的onContextItemSelected(MenuItem item)方法.