Fetch AutoCompleteTextView suggestions from service in separate thread

后端 未结 3 2174
醉话见心
醉话见心 2021-02-09 16:57

For my AutoCompleteTextView I need to fetch the data from a webservice. As it can take a little time I do not want UI thread to be not responsive, so I need somehow

3条回答
  •  离开以前
    2021-02-09 17:45

    EDITED: Added naive way to avoid the dropdown showing when you click a suggestion.

    I do something like this in my app:

    private AutoCompleteTextView mSearchbar;
    private ArrayAdapter mAutoCompleteAdapter;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mAutoCompleteAdapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line);
        mSearchbar = (AutoCompleteTextView) findViewById(R.id.searchbar);
        mSearchbar.setThreshold(3);
        mSearchbar.setAdapter(mAutoCompleteAdapter);
        mSearchbar.addTextChangedListener(new TextWatcher() {
    
            private boolean shouldAutoComplete = true;
    
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                shouldAutoComplete = true;
                for (int position = 0; position < mAutoCompleteAdapter.getCount(); position++) {
                    if (mAutoCompleteAdapter.getItem(position).equalsIgnoreCase(s.toString())) {
                        shouldAutoComplete = false;
                        break;
                    }
                }
    
            }
    
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
    
            @Override
            public void afterTextChanged(Editable s) {
                if (shouldAutoComplete) {
                    new DoAutoCompleteSearch().execute(s.toString());
                }
            }
        }
    }
    
    private class DoAutoCompleteSearch extends AsyncTask> {
        @Override
        protected ArrayList doInBackground(String... params) {
            ArrayList autoComplete = new ArrayList();
            //do autocomplete search and stuff.
            return autoComplete;
        }
    
        @Override
        protected void onPostExecute(ArrayList result) {
            mAutoCompleteAdapter.clear();
            for (String s : result)
                mAutoCompleteAdapter.add(s);
        }
    }
    

提交回复
热议问题