Android: registering a ContextMenu for a custom list
I made my own list adapter extending the base adapter. Each item in the list has an image button, 2 text boxes, and a button. I tried adding a context menu to the list box to show some options for an item in the list.
registerForContextMenu(getListView());
I used the MenuInflater object to inflate the context menu XML file. But when you click on items in the list, nothing is displayed or the usual highlighting of the list item is not displayed when clicked. Doesn't the context menu work for custom lists? Any help would be much appreciated.
Regards, Primal
a source to share
Make sure the children of the ListView must be Long Clickeable.
This can be done in the xml layout file, for example:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:longClickable="true">
<!-- Child elements -->
</LinearLayout>
Or it can be done in java code:
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
CustomView customView = new CustomView();
customView.setLongClickeable(true);
}
Hope this helps.
a source to share
Call registerForContextMenu where appropriate, onCreateView or onCreate.
registerForContextMenu(getListView());
Implement into your adapter as shown below.
public class CustomeLabelAdpater extends BaseAdapter implements View.OnCreateContextMenuListener{
Place this line in your getView method.
vi.setOnCreateContextMenuListener(this);
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
vi.setOnCreateContextMenuListener(this);
}
Place this method blank in your adapter.
public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
// empty implementation
}
Then you override onCreateContextMenu and onContextItemSelected in your fragment or activity.
@Override
public void onCreateContextMenu(ContextMenu contextMenu, View view,
ContextMenu.ContextMenuInfo contextMenuInfo) {
// create context the menu
Activity.getMenuInflater().inflate(R.menu.context_menu, contextMenu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.open:
return true;
default:
return super.onContextItemSelected(item);
}
}
a source to share
I had a similar problem using a custom adapter while extending ListActivity.
I found that I had to ensure that it gets setContentView
called before setOnCreateContextMenuListener
so that these events are logged properly.
Example:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getListView().setOnCreateContextMenuListener(this);
// do adapter calls etc here
}
Hope it helps.
a source to share