AutoCompleteTextView item selection programmatically

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

提交回复
热议问题