单击项目时,在列表视图中选择不同的元素

时间:2011-07-18 09:03:22

标签: java android

我有一个带有自定义适配器的列表视图,带有一个图像按钮和一个文本视图。

我想在图像按钮上按下时打开上下文菜单,如果按文本视图则打开另一个上下文菜单。

我该怎么做?

这是我的onClickListener

lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            if (id == view.findViewById(R.id.label).getId()) //label press
            {
                TextView text = (TextView) view.findViewById(R.id.label);
                registerForContextMenu(text);
                openContextMenu(text);
            }
            else //imageButton press
            {
                ImageButton ib= (ImageButton) view.findViewById(R.id.image);
                registerForContextMenu(ib);
                openContextMenu(ib);
            }
         }
       });

2 个答案:

答案 0 :(得分:0)

将OnCreateContextMenuListener添加到视图中:

    text.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) {
                menu.setHeaderTitle("Text context menu");
                menu.add(ContextMenu.NONE, MY_OPTION_CONTEXT_MENU, ContextMenu.NONE, "Some option");
            }
        });

在您的活动视图中:

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

    switch(item.getItemId()) {
        case MY_OPTION_CONTEXT_MENU:
            TextView v = (TextView) info.targetView;
            // more code here
            return true;
    }

    return super.onContextItemSelected(item);
}

答案 1 :(得分:0)

public View getView(int position, View convertView,
                            ViewGroup parent) {
        LayoutInflater inflater=getLayoutInflater();
        View row=inflater.inflate(R.layout.row_listview_with_icon, parent,  false);
        TextView label=(TextView)row.findViewById(R.id.label);

        ImageView icon=(ImageView)row.findViewById(R.id.icon);

        final int m_pos = position;
                    label.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                ...             
            }
        });
        icon.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                ...             
            }
        });

        return(row);
    }