Select distinct elements in listview when click item
I have a list view with custom adapter, with an Image But开发者_JAVA百科ton and a Text View.
I want to open a context menu when a press is made on the Image Button, and open another context menu if i press the Text View.
How can I do this??
This is my 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);
}
}
});
Add OnCreateContextMenuListener to the view:
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");
}
});
In your activity view:
@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);
}
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);
}
精彩评论