Подтвердить что ты не робот

Android Spinner OnItemSelected не вызывается с тем же элементом

Прежде всего, я знаю, что об этом спрашивали несколько раз, но на более новых версиях Android похоже, что предложенные решения не работают. Мне нужно, чтобы мой спиннер вызывал OnItemSelected даже тогда, когда пользователь выбирает один и тот же элемент дважды. Я нашел этот класс, который должен добиться цели:

    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);
    }
}

Этот факт работает, но в нем есть ошибка: он вызывает дважды элемент в первый раз :( Кто-нибудь может сказать мне, как я могу решить эту проблему?

Спасибо товарищи.

4b9b3361

Ответ 1

Я решил использовать этот класс:

public class NDSpinner extends Spinner {

      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 public void
      setSelection(int position, boolean animate)
      {
        boolean sameSelected = position == getSelectedItemPosition();
        super.setSelection(position, animate);
        if (sameSelected) {
          // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
          getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
        }
      }

      @Override public void
      setSelection(int position)
      {
        boolean sameSelected = position == getSelectedItemPosition();
        super.setSelection(position);
        if (sameSelected) {
          // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
          getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
        }
      }
    }

Спасибо в любом случае:)

Ответ 2

Для меня я расширил AppCompatSpinner.

Также, если ваш Spinneris в XML для макета, не забудьте изменить свой

<Spinner...

to

<com.example.util.NDSpinner...