Dannie
Dannie

Reputation: 175

Don't set text value to AutoCompleteTextView on item click

I have an AutocompleteTextView on my screen. By default, when user clicks on an item of an autocompletetextviews's dropdown item, it sets the text of this autocompletetextview to this chosen item value.

Is there any way to disable this? So when user clicks on a dropdown item, only onItemClickListener triggered?

Setting value to "" in onItemClickListener is not an option.

autoCompleteTextView.setOnItemClickListener { adapterView, view, i, l -> 
    autoCompleteTextView.setText("")
}

As I need my TextWatcher to not be triggered

Upvotes: 6

Views: 2417

Answers (1)

Ben P.
Ben P.

Reputation: 54204

AutoCompleteTextView uses this class to detect clicks on its dropdown:

private class DropDownItemClickListener implements AdapterView.OnItemClickListener {
    public void onItemClick(AdapterView parent, View v, int position, long id) {
        performCompletion(v, position, id);
    }
}

Inside that performCompletion() method, there is this call to actually change the contents of the TextView:

replaceText(convertSelectionToString(selectedItem));

This replaceText() method is protected, which means you can create a subclass of AutoCompleteTextView and override it to do nothing:

public class MyAutoCompleteTextView extends AppCompatAutoCompleteTextView {

    public MyAutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void replaceText(CharSequence text) {
        // do nothing
    }
}

Now just replace your <AutoCompleteTextView> tags with <com.example.yourprojecthere.MyAutoCompleteTextView> tags and you should be all set.

Upvotes: 9

Related Questions