First of all, I know that this has been asked several times, but on newer versions of Android it seems that the proposed solutions do not work. I need my spinner to call OnItemSelected even when the user selects the same element twice. I found this class that should do the trick:
public class NDSpinner extends Spinner { private int lastSelected = 0; private static Method s_pSelectionChangedMethod = null; static { try { Class noparams[] = {}; Class targetClass = AdapterView.class; s_pSelectionChangedMethod = targetClass.getDeclaredMethod("selectionChanged", noparams); if (s_pSelectionChangedMethod != null) { s_pSelectionChangedMethod.setAccessible(true); } } catch( Exception e ) { Log.e("Custom spinner, reflection bug:", e.getMessage()); throw new RuntimeException(e); } } public NDSpinner(Context context) { super(context); } public NDSpinner(Context context, AttributeSet attrs) { super(context, attrs); } public NDSpinner(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { if(this.lastSelected == this.getSelectedItemPosition()) testReflectionForSelectionChanged(); if(!changed) lastSelected = this.getSelectedItemPosition(); super.onLayout(changed, l, t, r, b); } public void testReflectionForSelectionChanged() { try { Class noparams[] = {}; s_pSelectionChangedMethod.invoke(this, noparams); } catch (Exception e) { Log.e("Custom spinner, reflection bug: ", e.getMessage()); e.printStackTrace(); } } @Override public void onClick(DialogInterface dialog, int which) { super.onClick(dialog, which); } }
This fact works, but it has an error: it calls the element twice for the first time :( Can anyone tell me how I can solve this problem?
Thank you comrades.
android android spinner spinner
Luca D'Amico
source share