AutoCompleteTextView results empty on space

2019-07-18 01:48发布

I have an AutoCompleteTextView, and it works nicely, until I add a space to my input. If i had, say, a list of many historical events (Battle of Britain (1940), Battle of the Bulge (1944), [insert lots of battles], Napoleon's fatal march (1812), [insert lots other historical events]).

When I enter "Battle" or "battle", I get a list of all battles (although it seems there is a max), and when I enter "britain", the "Battle of Britain (1940)" appears in the results. However, when I enter a space after "Battle", all result entries disappear.

I read can't really find any helpful posts or questions regarding this topic besides this, but that didn't give me any answers.

Is there a way to have the AutoCompleteTextView keep autocompleting after the insertion of a space?

Edit: I don't really see the point of adding code, as it's just an AutoCompleteTextView with an Adapter with Strings, but alright, this happens in onCreate():

auto = (AutoCompleteTextView) findViewById(R.id.auto);
String[] events = getListOfEvents();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, events);
auto.setAdapter(adapter);

where getListOfEvents() simply reads an puts all historical events in a String[]

1条回答
Juvenile、少年°
2楼-- · 2019-07-18 02:09

The auto complete breaks when inserting that space character because under the hood it uses the filter from the adapter that is set on the AutoCompleteTextView(ArrayAdapter in your case). The filter for the default ArrayAdapter uses spaces as a delimiter to break the text of each adapter's row into words which are then tested against the filter input. This will provide no results because the input filter(which has a space in it) will not match any of the words from the row(as those words don't have the space at the end). For example the row "Battle of Britain" will not match "Battle " because "Battle " will not match any of the words "Battle", "of" or "Britain" which result from splitting the initial text after " ".

If you want to make it work you'll have to implement your own Adapter which will return a Filter that takes in consideration that space after a word.

查看更多
登录 后发表回答