Domanda

I had to recreate the functionality of AutoCompleteTextViews with EditTexts (for different reasons* & that's probably another question, but i'm down that path now).

I've got all my functionality working by issuing my api calls whenever the Text on my EditText changes. I do this by using TextWatcher (overriding the afterTextChanged method).

Is there a way i can control, the way the calls are fired with the listener?

Here's my use case:

I'm searching for California.

I check for a min. length of 3 and then start firing calls. so number of API calls currently sent = 8

  1. Cal
  2. Cali
  3. Calif
  4. Califo
  5. Califor
  6. Californ
  7. Californi
  8. California

Is there a way I can cancel off fired events, if i receive a new text change? So when the user types California, i wait until there's a gap where no new text is entered, and then fire a call to my API?

It doesn't have to be very accurate. An additional event fire here and there is completely acceptable. I'm looking to reduce the number of events fired from 8 to atleast 3.

I wanted to show the autocomplete results in a different listview vs. the pop-up window that comes alongside the auto-complete textview.

È stato utile?

Soluzione

Try following TextWatcher:

TextWatcher t = new TextWatcher() {
        long lastChange = 0;

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {

            // TODO Auto-generated method stub
            if (s.length() > 3) {
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        if (System.currentTimeMillis() - lastChange >= 300) {
                            //send request
                        }
                    }
                }, 300);
                lastChange = System.currentTimeMillis();

            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top