0

I can successfully display an alert dialog with a list. What I'm trying to achieve is to scroll to a specific position of this list. Is there a way to do this? Below there is the code


fun createAlert(activity: Activity, mandatory: Boolean, provinceSelected: (Int) -> Unit) {
        val provinceDialog: AlertDialog.Builder = AlertDialog.Builder(activity)
        provinceDialog.setTitle(activity.getString(R.string.select_province_from_list))
        provinceDialog.setCancelable(!mandatory)
        val arrayAdapter = ArrayAdapter<String>(activity, R.layout.province_list_row_item, SubAdministrativeAreas.provincesList)
        provinceDialog.setAdapter(arrayAdapter
        ) { _, positionSelected ->
            provinceSelected(positionSelected)
        }
        
        
        /**
         * Here I should move to an adapter position
         */
        
        
        provinceDialog.show()
    }

Nimantha
  • 6,405
  • 6
  • 28
  • 69

2 Answers2

2

You can use AlertDialog to get the list and after show you can scroll to a certain position.

Try this way it should work .

fun createAlert(activity: Activity, mandatory: Boolean, provinceSelected: (Int) -> Unit) {
    val provinceDialog: AlertDialog.Builder = AlertDialog.Builder(activity)
    provinceDialog.setTitle(activity.getString(R.string.select_province_from_list))
    provinceDialog.setCancelable(!mandatory)
    val arrayAdapter = ArrayAdapter<String>(activity, R.layout.province_list_row_item, SubAdministrativeAreas.provincesList)
    provinceDialog.setAdapter(arrayAdapter
    ) { _, positionSelected ->
        provinceSelected(positionSelected)
    }
    val dialog = provinceDialog.create()
    dialog.setOnShowListener {
            dialog.listView.smoothScrollToPosition(11)
    }
    dialog.show()
}
ADM
  • 20,406
  • 11
  • 52
  • 83
1

You can retrieve the ListView an AlertDialog uses via AlertDialog.getListView().

There are then a few easy ways to scroll the list programmatically, this post seems to cover it - Programmatically scroll to a specific position in an Android ListView.

Henry Twist
  • 5,666
  • 3
  • 19
  • 44