So I’m interested in creating a custom context menu for each of my list items when they are long clicked. I saw this implemented in the Baconreader app, and thought it would be as simple as:
- Create one LinearLayout (or whatsoever) when populating the listview
- When an item is long-clicked, hide the item (View.GONE) and add the LinearLayout to the list item’s parent.
- When needed, show the list item and remove the LinearLayout from it’s parent.
I successfully managed to hide the list items onItemLongClick, but it turns out that you can’t add Views to a ListView (d’oh). But that’s got to be the way Baconreader does it. I can’t figure it out. Here’s some code I tried:
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
arg1.setVisibility(View.GONE); // hide the list item, works
// trying to add a TextView after a list
// item's position, doesn't work.
listView.addView(textView, arg2);
return true;
}
});
Here’s a sample what it should look like:
So the List Item is hidden and a custom context menu (seems like a ViewGroup) is placed directly over the list item’s position. But how?
Edit: Solved. The updated code:
list_item.xml
<TextView
android:id="@+id/list_item_title"
.....
/>
</FrameLayout>
The java code
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
((FrameLayout)arg1).addView(w);
return true;
}
});
And of course you have to use SimpleAdapter instead of ArrayAdapter.
Just a quick tip: what if you don’t hide the list item and add the context menu to the list, but instead add the context menu to the list item?
For example, wrap the current layout of the list item into a FrameLayout. Then when long-clicked, just add the context menu to this FrameLayout instead? (and if needed hide the first child of the FrameLayout). This wouldd also guarantee that the context menu will have the same size as the list item.