How can I avoid autocomplete dropdown appearing when text is programmatically set?

一世执手 提交于 2019-12-03 22:51:54

If you want to support API<17, Subclass AutoCompleteTextview and override setText(text, filter) method

@Override
public void setText(CharSequence text, boolean filter) {
    if(Build.VERSION.SDK_INT>=17) {
        super.setText(text, filter);
    }else{
        if(filter){
            setText(text);
        }else{
            ListAdapter adapter = getAdapter();
            setAdapter(null);
            setText(text);
            if(adapter instanceof ArrayAdapter)
                setAdapter((ArrayAdapter) adapter);
            else
                setAdapter((CursorAdapter) adapter);
            //if you use more types of Adapter you can list them here
        }
    }
}

Then whenever you want to set the text manually call setText(text, false)

user1145201

This works fine for me and is less complex:

ListAdapter adapter = autoCompleteTextView.getAdapter();
autoCompleteTextView.setAdapter(null);
autoCompleteTextView.setText("whatever");
autoCompleteTextView.setAdapter(adapter);

Looks like its a problem of the order how messages are processed. My work around looks like this:

//autoCompleteTextView.dismissDropDown();
new Handler().post(new Runnable() {
    public void run() {
        autoCompleteTextView.dismissDropDown();
}});

My solution (but I don't like it, there must be something better):

autoCompleteTextView.setText(valueFromAlternativeSource);
autoCompleteTextView.setDropDownHeight(0);

autoCompleteTextView.setOnKeyListener(new OnKeyListener(){

   @Override
   public boolean onKey(View v, int keyCode, KeyEvent event) {
       autoCompleteTextView.setDropDownHeight(LayoutParams.WRAP_CONTENT);
   }
}
autoCompleteTextView.setText(valueFromOtherMeans, filter);

     * @param filter If <code>false</code>, no filtering will be performed
     *        as a result of this call.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!