OnLongClickListener for a Spinner in Android L is not working. Any solutions?

1.3k views Asked by At

I had an Alertbox show up when the user long presses on a spinner. It worked fine for Android 4.4 and below, but for Android L (5.0) the long click is not registering at all. Has anyone else seen this issue or have a workaround?

Here is the code

classArrayAdapter =   new ArrayAdapter<String> (getApplicationContext(),  R.layout.class_item,          displayClassNames);
classArrayAdapter.setDropDownViewResource(R.layout.class_dropdown);

classSpinner = new Spinner(this);
classSpinner.setAdapter(classArrayAdapter);
classSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
     // spinner code here - spinner works fine
}

classSpinner.setOnLongClickListener(new OnLongClickListener() 
    {
       @Override
        public boolean onLongClick(View v) 
        {
            if(UI==true)
            {
                studentsPresent();
            }
            else
            {
                studentsPassing();
            }
            return true;
        }
    });
1

There are 1 answers

2
Almighty On

You need to set OnLongClickListener on items of your adapter. Since I was using ArrayAdapter, I had to subclass it and override the getView method like this:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final View view = super.getView(position, convertView, parent);
    if (onLongClickListener != null && convertView == null) { //set listener only for newly created view
        view.setLongClickable(true);
        view.setOnLongClickListener(onLongClickListener);
    }
    return view;
}

The onLongClickListener field is set in adapter's constructor.