AutoCompleteTextView item selection programmatically

前端 未结 9 2056
故里飘歌
故里飘歌 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:19

    The problem is that you are setting a text and the AutoCompleteTextView is only showing words that match with that text. A non elegant way of solving this is to set an high threshold (at least the max length of the names of the cities) to force Android to show you all the values of your list (this threshold is the number of characters that the field must have to search similarities).

    0 讨论(0)
  • 2021-02-18 15:20

    Using the Nilton Vasques solution it can be so:

    with(autoComplete) {
        setAdapter(this@YourFragment.adapter)
        setText(itemText)
        showDropDown()
        listSelection = if (itemIndex > 0) itemIndex - 1 else 0 // Because AutoCompleteTextView shows the next row.
        performCompletion()
    }
    

    Notice, that it will show a drop-down list, otherwise listSelection won't work. If you call dismissDropDown(), the item won't be selected. If you don't want to show the drop-down list, you can use setOnTouchListener to capture opening the list, but it hardly will help (you should resolve a filtering problem).

    setOnTouchListener { _, event ->
        if (event.action == MotionEvent.ACTION_DOWN) {
            showDropDown()
            listSelection = if (itemIndex > 0) itemIndex - 1 else 0
            performCompletion()
            requestFocus()
        }
        false
    }
    
    0 讨论(0)
  • 2021-02-18 15:22
    autoComplete.setListSelection(position);
    
    0 讨论(0)
提交回复
热议问题