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

JMR*_*ies 5 android

在此输入图像描述

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

在此输入图像描述

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

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

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

所以我尝试了这个:

@Override
public void onMoreClicked(ArtistsListItem item, int position, View imageButton) {       
     registerForContextMenu(imageButton);
}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

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

我正在使用ActionBarSherlock,我不知道这是否有所作为,但我想这值得注意.

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

nan*_*ana 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;
}
Run Code Online (Sandbox Code Playgroud)

在片段中我只听 onClick 事件:

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

或者您可以使用PopupMenu支持 v7,您可以在 Android studio 中安装它,而无需从“项目结构”窗口中进行 gradle。

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

  • 是的,我很确定你可以这样做 -> public void onListItemClick(ListView lv, View v, int position, long id){ lv.showContextMenuForChild(v); } (4认同)