1. 程式人生 > >How Android's AutoCompleteTextView Nearly Drove me Nuts

How Android's AutoCompleteTextView Nearly Drove me Nuts

AutoCompleteTextView is a nice widget Android provides. It helps the user enter text by presenting him possible selections based on what he has entered so far.

AutoCompleteTextView showing its dropdown
AutoCompleteTextView showing its dropdown

As a short recap: You have to provide a ListAdapter that also must implement the Filterable interface. The filterable adapter is used to define which proposals the Widget will display.

Everything is fine with an AutoCompleteTextView if you set the adapter and only the user enters some text and selects the proposal he is looking for.

But it get's complicated if you want to set the value programmatically. Setting it in your code causes the dropdown to appear - though that's not what anyone would want in this case. At least that was not what was needed in a project I'm working on.

But nevermind, the widget has the method dismissDropDown(). Surely this can be used to - well - dismiss the dropdown. Or to be more precise to stop it from appearing in the first place.

But no, that's not what's happening. Instead the popup gets displayed as if I hadn't called dismissDropdown(). But why?

What actually happens is that the setText(CharSequence) method causes some asynchronous methods to start: Whenever the text changes, the filter of the Adapter is used to filter for possible proposals to show. And since the filter can take a long time, it is called asynchronously. Some time later the filter returns and its results get displayed when the UI thread gets processing time again. At this point in time the dismissDropDown() method has long been completed - which is why this method has no effect whatsoever.

Annoying is, that there is a method in the AutoCompleteTextView's source that does exactly what we want:


public void setText(CharSequence text, boolean filter)

With the second boolean parameter you can decide whether any filtering should happen - and without filtering no dropdown would pop up.

Alas it is hidden and we cannot use it as of now. This method is waiting for "API council approval". When and if this gets approved I do not know. If you do not have the Android code available you can have a look at the source on GrepCode.

But if you look at the code of AutoCompleteTextView you can see a possible solution anyway. In the doAfterTextChanged() method of the internal TextWatcher object we see this fragment:


if (mFilter != null) {
   mPopupCanBeUpdated = true;
   performFiltering(getText(), mLastKeyCode);
}

The performFiltering() method is what starts the asynchronous filtering process so if this method isn't called all is nice and well.

The attribute mFilter on the other hand gets set in AutoCompleteTextView's setAdapter() method:


if (mAdapter != null) {
   //noinspection unchecked
   mFilter = ((Filterable) mAdapter).getFilter();
   adapter.registerDataSetObserver(mObserver);
} else {
   mFilter = null;
}

So the solution is to set the adapter to null before setting the text and directly afterwards setting it again to its old value.

Phew! This all took way too much time! But now it works. And in the end that's all that counts.

相關推薦

How Android's AutoCompleteTextView Nearly Drove me Nuts

AutoCompleteTextView is a nice widget Android provides. It helps the user enter text by presenting him possible selec

How We Do Automatic Token Refreshing using Androids New Work Manager

Just before all hope was lost, Evernote’s wonderful engineering team came up with a solution to this gap that has been created. Their Android-Job library b

python's seventh day for me

不改變 [1] mce list 調用 rem 元祖 int dai 數據類型的補充:     對於元祖: 如果只有一個元素,並且沒有逗號,此元素是什麽數據類型,該表達式就是什麽數據類型。 tu = (‘顧清秋‘) tul = (‘顧清秋‘,) print(type(t

python's eleventh day for me

war 什麽是 ret inner tar 緩存 url append 函數名 python2 中沒有nonlocal。 函數名是什麽?     函數名就是函數的名字, 本質:變量,特殊的變量。 1.單獨打印函數名: def func(): print(666)

python's sixth day for me 員工信息表

索引 無需 spl class 系統 pwd div 獲取 args import os user_dic = { ‘username‘:None, ‘password‘:None, ‘login‘:True } flag = False nam

python's thirty day for me 異常處理

IT raise class pri rate exceptio bre UC try ---恢復內容開始--- 程序的異常:報錯之後程序終止。   異常處理搭配使用: l = [‘創建老師‘,‘創建學校‘] while True: try: fo

ionic打包報錯:You have not accepted the license agreements of the following SDK components: [Android S

錯誤資訊: ...... You have been opted out of telemetry. To change this, run: cordova telemetry on. Android Studio project detected ANDROID_HOME=C:\User

Everything every Android Developer must know about new Android's Runtime Permission

Android M's name was just announced officially days ago. The final version is almost there and would be released not so long. Although A

Some Thoughts on Android's new ConstraintLayout and Android Studio's new Design Editor

At this year's IO Google introduced a new layout - the ConstraintLayout - and also presented it's totally revamped la

Android's ConstraintLayout: Align One View's Edge to Another View's Center

As you can see from the following excerpt of ConstraintLayout's supported attributes, there is no layout_constraintSt

How Apple’s First HQ Shaped the Company into What It Is Today

This story is for Medium members.Continue with FacebookContinue with GoogleMedium curates expert stories from leading publishers exclusively for members (w

How Decentralized Application Development Nearly Destroyed My World

How Decentralized Application Development Nearly Destroyed My WorldBy Rob Misiorowski, OpenBazaar Front End DeveloperOk, that title is a little hyperbolic,

This is how Tesla's Autopilot system sees the idyllic streets of Paris

Navigating Paris' chaotic streets requires a high level of attentiveness to avoid colliding with another car, a herd of scooters, a pedestrian, or a garbag

How Amazon's DeepLens seeks to rewire the old web with new AI

Every Amazon Echo, Google Home, Sonos One, or similar device in your house that recognizes your voice, and every smartphone through which you've ever spoke

How Microsoft's caricature AI turns photos into portrait cartoons

To become an outstanding cartoonist can take years of practice, but that skill -- or at least the facial caricature part -- has now been automated by a gro

ionic打包報錯:You have not accepted the license agreements of the following SDK components:   [Android S

錯誤資訊: ...... You have been opted out of telemetry. To change this, run: cordova telemetry on. Android Studio project detected ANDROID_HO

ImageView的Scaletype決定了圖片在View上顯示時的樣子,如進行何種比例的縮放,及顯示圖片的整體還是部分,等等。 設定的方式包括: 1. 在layout xml中定義Android:s

ImageView的Scaletype決定了圖片在View上顯示時的樣子,如進行何種比例的縮放,及顯示圖片的整體還是部分,等等。 設定的方式包括: 1. 在layout xml中定義Android:scaleType="CENTER" 2. 或在程式碼中呼叫i

A First Glance at Android's RecyclerView

At this year's Google I/O, Google released a preview to the upcoming Android version. The so called L Developer Previ

Use Android's ContentObserver in Your Code to Listen to Data Changes

When you are using a content provider as a client, chances are that you want to know whenever the data changes. That'

What You Need to Know About the Intents of Android's Calendar App

When your app needs to access calendar data you have to choose whether to use the CalendarContract content provider o