Skip to content

Instantly share code, notes, and snippets.

@furycomptuers
Forked from anonymous/InstantAutoComplete
Last active June 24, 2020 14:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save furycomptuers/4961368 to your computer and use it in GitHub Desktop.
Save furycomptuers/4961368 to your computer and use it in GitHub Desktop.
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
public class InstantAutoComplete extends AutoCompleteTextView {
public InstantAutoComplete(Context context) {
super(context);
}
public InstantAutoComplete(Context arg0, AttributeSet arg1) {
super(arg0, arg1);
}
public InstantAutoComplete(Context arg0, AttributeSet arg1, int arg2) {
super(arg0, arg1, arg2);
}
@Override
public boolean enoughToFilter() {
return true;
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
if (getWindowVisibility() == View.GONE) {
Log.d("InstantAutoComplete", "Window not visible, will not show drop down");
return;
}
if (focused) {
performFiltering(getText(), 0);
showDropDown();
}
}
}
@Miha-x64
Copy link

This silently ignores the situation when focus gets restored on configuration change. I've ended up using View#post:

class InstantAutoComplete(context: Context) : AutoCompleteTextView(context) {
    override fun enoughToFilter(): Boolean = true
    override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect)
        if (focused && adapter != null)
             if (!maybeShowSuggestions())
                 post { maybeShowSuggestions() }
    }
    private fun maybeShowSuggestions(): Boolean =
        if (windowVisibility == View.VISIBLE) {
            performFiltering(text, 0)
            showDropDown()
            true
        } else {
            false
        }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment