How to detect if the Spinner is click open on Android
Asked Answered
T

1

6

I have a spinner and I want to detect when the user clicked on it. When the user clicks it open, I want to call an endpoint and then update the spinner with new data. But I couldn't figure out how to do this and results in infinite loop:

I call the API in here:

public View getDropDownView(int position, View convertView, ViewGroup parent) {
  // Call API here
  // Do render with old data.
}

when the API successes, I call the to update:

@Override
public void onSuccess(final Response response) {
  Helper.update(...);
}


public void update(...) {
  ...
  adapter.setItems(newData);
  adapter.notifyDataSetChanged();
}

and then this triggers getDropDownView() again. I couldn't figure out what else is called after the user clicks open the spinner besides getDropDownView(). How can I solve this problem?

Takahashi answered 11/2, 2016 at 2:32 Comment(0)
A
16

You can set Touch-listener on Spinner to detect click.

 findViewById(R.id.spinner).setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Toast.makeText(MainActivity.this,"CallAPI",Toast.LENGTH_SHORT).show();
            return false;
        }
    });

And return False from onTouch to behave normally.I hope It will work for you.

Acadia answered 11/2, 2016 at 2:52 Comment(1)
note instead of returning false, you should return View v.performOnClick() for it to work normal, and also this onTouch is called both when the spinner is clicked to open and close the items.Shafting

© 2022 - 2024 — McMap. All rights reserved.