I have this code
spinner.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (parent.getItemAtPosition(position).equals("Choose an article")){
}else {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(),"long click: " +item, Toast.LENGTH_SHORT).show();
}
return false;
}
});
When I debug the code, on long click item event does nothing. The code inside onItemLongClick() is never executed. How can I fix it?
Spinnerin Android might not support thesetOnItemLongClickListener, due to its UI nature - it is essentially a dialog or dropdown menu. The dropdown menu will close after a short click, so a long click listener is not applicable here, hence why your long click listener is not triggered.If you want to add additional interaction to the spinner, you could use the normal
setOnItemSelectedListenerinstead.(Examples here, and "Android - Text is Pushed to the Left in a Spinner")
You would then have to implement your own time logic if you want to simulate a long click event.
But, since the
onTouchmethod is not a part of theOnItemSelectedListenerinterface, we will need a different approach to simulate a long press on theSpinner. As mentioned, it does not natively support long clicks: one approach would be to create a customSpinnerclass where you can manage touch events yourself. A very basic implementation would be:You can use this
LongClickSpinnerin your XML layouts like a normalSpinner. When the user touches the spinner for longer thanLONG_PRESS_TIMEmilliseconds, your "long click" action will execute.That solution is still a workaround and might not fit all use cases. Spinner is not intended to handle long press events, and its behavior with this custom implementation might not be perfect.
If you need a different interaction paradigm for the selection of items, you might want to consider using another UI component that does support long clicks, such as a
ListVieworRecyclerView.With
ListVieworRecyclerView, you can have a list of items that support both normal clicks (for selection of the item) and long clicks (for showing additional options for example). The long click implementation would then look like this:The difference between using a
ListVieworRecyclerViewand aSpinneris that theListView/RecyclerViewwould always be visible on your layout, while aSpinnerwould only display its items once it's tapped.If you want the spinner-like behavior while having the
setOnItemLongClickListenerfunctionality, one option would be to create a custom dialog that contains aListVieworRecyclerView. This way, you could emulate the spinner behavior with the benefits of long click listener support.