AutoCompleteTextView item selection programmatically

前端 未结 9 2059
故里飘歌
故里飘歌 2021-02-18 14:41

I have an autocomplete text view that is filled with cities from an sqlite database that calls an async task on item click, recently I added an option to detect my location usin

9条回答
  •  野的像风
    2021-02-18 15:06

    I have used autoCompleteTextView.setText(myText, false); solution as well, however it sometimes failed. I mean it was actively filtering results so, when user clicks there was only 1 item at dropdown.

    In addition I also needed this to work on custom objects as well, and this is my my solution:

    binding.hourEditText.configureDropDownMenu(viewModel.hours) { it.hourString() }
        .subscribe {
            // Do whatever you need when on click.
        }
        .addTo(disposables)
    
    fun  AutoCompleteTextView.configureDropDownMenu(list: List, toString: ((T) -> String)? = null): Observable {
        keyListener = null
        val textItems = toString?.let(list::map) ?: list.map { it.toString() }
        setAdapter(NonFilterArrayAdapter(context!!, android.R.layout.simple_spinner_dropdown_item, textItems))
        return itemClickEvents().map {
            list[it.position]
        }
    }
    
    private class NonFilterArrayAdapter(context: Context, @LayoutRes resource: Int, objects: List) : ArrayAdapter(context, resource, objects) {
    
        override fun getFilter() = NonFilter()
    
        private class NonFilter : Filter() {
            override fun performFiltering(constraint: CharSequence?) = FilterResults()
    
            override fun publishResults(constraint: CharSequence?, results: FilterResults?) = Unit
        }
    }
    

    Note: This also contains a bit of Rx, but it can be removed easily.

提交回复
热议问题