单击listview项目内的元素创建上下文菜单

时间:2013-10-25 00:40:02

标签: android

enter image description here

点击更多图标(固定在列表项右侧的3个垂直点)打开Goog​​le音乐中的上下文菜单:

enter image description here

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

  

如果您的活动使用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,我不知道这是否有所作为,但我想这值得注意。

有没有人知道这里发生了什么?

1 个答案:

答案 0 :(得分: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;
}

在Fragment中我只是听onClick事件:

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

或者您可以使用来自支持v7的PopupMenu您可以在Project Studio窗口中安装没有gradle的Android Studio。

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