从listview适配器单击按钮时显示的上下文菜单

时间:2016-03-30 15:49:37

标签: android listview contextmenu

我在ListView上有一个按钮,点击该按钮我想在我的布局中显示一个上下文菜单。

问题是customerlistadapter无法识别方法registerForContextMenu。 上下文菜单方法onCreateContextMenuonContextItemSelected会在显示ListView的活动中被覆盖。

    @Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.customforumview, null);
        holder = new ViewHolder();
        holder.txtTitle = (TextView) 
        convertView.findViewById(R.id.forumtitle);
        holder.txtCategory = (TextView)
        convertView.findViewById(R.id.forumcategory);
        holder.menubutton = (ImageButton)
        convertView.findViewById(R.id.menuselect);

        holder.menubutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               //context menu to be called here 
            }
        });
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    holder.txtTitle.setText(searchArrayList.get(position).getTitle());
    holder.txtCategory.setText(searchArrayList.get(position).getCategory());

    return convertView;
}

1 个答案:

答案 0 :(得分:2)

如果您在Activity中正确注册了contextMenu,则可以使用以下命令调用contextMenu:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ...
    holder.menubutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //context menu to be called here
            parent.showContextMenuForChild(v); 
        }
    ...
});

如果您想要访问活动中调用的元素,请添加onCreateContextMenu这样的

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
  super.onCreateContextMenu(menu, v, menuInfo);
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.context_menu, menu);

  AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
  long itemID = info.position;
  menu.setHeaderTitle("lior" + itemID);
}

请参阅@Lior Iluz answer

了解更多信息

希望这会有所帮助!!