Android: AutoCompleteTextView show suggestions when no text entered

后端 未结 14 1943
-上瘾入骨i
-上瘾入骨i 2020-11-27 11:20

I am using AutoCompleteTextView, when the user clicks on it, I want to show suggestions even if it has no text - but setThreshold(0) works exactly

14条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 12:07

    Seven years later, guys, the problem stays the same. Here's a class with a function which forces that stupid pop-up to show itself in any conditions. All you need to do is to set an adapter to your AutoCompleteTextView, add some data into it, and call showDropdownNow() function anytime.

    Credits to @David Vávra. It's based on his code.

    import android.content.Context
    import android.util.AttributeSet
    import android.widget.AutoCompleteTextView
    
    class InstantAutoCompleteTextView : AutoCompleteTextView {
    
        constructor(context: Context) : super(context)
    
        constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    
        constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
    
        override fun enoughToFilter(): Boolean {
            return true
        }
    
        fun showDropdownNow() {
            if (adapter != null) {
                // Remember a current text
                val savedText = text
    
                // Set empty text and perform filtering. As the result we restore all items inside of
                // a filter's internal item collection.
                setText(null, true)
    
                // Set back the saved text and DO NOT perform filtering. As the result of these steps
                // we have a text shown in UI, and what is more important we have items not filtered
                setText(savedText, false)
    
                // Move cursor to the end of a text
                setSelection(text.length)
    
                // Now we can show a dropdown with full list of options not filtered by displayed text
                performFiltering(null, 0)
            }
        }
    }
    

提交回复
热议问题