5

在此处输入图像描述

单击更多图标(锚定在列表项右侧的 3 个垂直点)会在 Google 音乐中打开一个上下文菜单:

在此处输入图像描述

我正在尝试使用我猜测的上下文菜单来重新创建它。文档说:

如果您的 Activity 使用 ListView 或 GridView,并且您希望每个项目提供相同的上下文菜单,请通过将 ListView 或 GridView 传递给 registerForContextMenu() 来为上下文菜单注册所有项目。

但我仍然希望列表项本身可点击。我只想在用户单击更多图标时显示上下文菜单,就像在 Google 音乐中所做的那样。

所以我尝试了这个:

@Override
public void onMoreClicked(ArtistsListItem item, int position, View imageButton) {       
     registerForContextMenu(imageButton);
}

onMoreClicked 只是我为从列表的适配器接收 onClick 回调而制作的自定义侦听器的一部分。

registerForContextMenu 被调用,但片段的 onCreateContextMenu 方法从未被调用:

@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo info) { //this method is never called
    super.onCreateContextMenu(menu, view, info);

    android.view.MenuInflater inflater = mActivity.getMenuInflater();
    inflater.inflate(R.menu.artist_list_menu, menu);
}

我运行了一些断点来检查它是否正在运行,但它从未运行过。我对活动的 onCreateContextMenu 做了同样的事情(registerForContextMenu 的类是片段,但只是为了确保我是这样做的),也没有骰子。

我正在使用 ActionBarSherlock,我不知道这是否会有所不同,但我想这值得一提。

有谁知道这里发生了什么?

4

1 回答 1

2

我有一个类似的问题,这就是我最终要做的事情:
在 listAdapter.getItem 我将一个侦听器附加到每个子视图:

private Fragment mParentFragment;

public FriendListAdapter(Fragment fragment, ...) {
    . . .
    this.mParentFragment = fragment;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if( convertView == null ){
        convertView = LayoutInflater.from(mContext).inflate(R.layout.friend_layout, parent, false);
    }
    ViewGroup viewGroup = (ViewGroup) convertView;
    assert viewGroup != null;

    *
    *
    *

    Button viewMessageButton = (Button) viewGroup.findViewById(R.id.b_send_message);
    viewMessageButton.setTag(friend.getHandle());
    viewMessageButton.setOnClickListener(mParentFragment);
    return viewGroup;
}

在片段中我只听 onClick 事件:

public class FriendListFragment extends Fragment implements View.OnClickListener {
    @Override
    public void onClick(View view) {
        dialog.show(getActivity().getSupportFragmentManager(), SEND_MESSAGE_DIALOG);
    }
}

或者您可以使用PopupMenu支持 v7,您可以在 Android Studio 中安装它,而无需从 Project Structure 窗口中使用 gradle。

选择Modules左侧,然后Import Library导航到..../android-studio/sdk/extras/android/support/v7/appcompat然后在您的主项目模块中添加appcompat作为模块依赖项。

于 2013-10-25T00:47:17.373 回答