如何滚动到 AlertDialog 中的特定列表位置

How to scroll to a specific list position inside AlertDialog

我可以成功显示带有列表的警告对话框。 我想要实现的是滚动到此列表的特定位置。有没有办法做到这一点? 下面是代码


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()
    }

您可以通过 AlertDialog.getListView().

检索 ListViewAlertDialog 使用

然后有一些简单的方法以编程方式滚动列表,这个 post 似乎涵盖了它 - Programmatically scroll to a specific position in an Android ListView

您可以使用AlertDialog获取列表,显示后您可以滚动到某个位置。

试试这个方法应该行得通。

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()
}