如何解决自定义 Alertdialog 中的下拉列表不显示任何项目 (Kotlin)
我想创建一个带有下拉列表和其他一些内容的自定义 Alertdialog 布局。我正在使用 Kotlin,而且我对它很陌生 目前我被困在下拉列表中,因为它没有显示任何内容
这是Layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/backButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:text="Zurück"
app:icon="@drawable/ic_baseline_arrow_back_24"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Spinner
android:id="@+id/pizzaSelection"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="100dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
这是我在活动中调用对话框的方式:
private fun showPizzaDialog(){
val pizzaDialogBuilder = AlertDialog.Builder(this)
pizzaDialogBuilder.setView(R.layout.pizza_alertdialog)
val pizzaDropdown = findViewById<Spinner>(R.id.pizzaSelection)
val pizzaTypes = resources.getStringArray(R.array.pizzaTypes)
if (pizzaDropdown != null) {
val adapter = ArrayAdapter(this,android.R.layout.simple_spinner_item,pizzaTypes)
pizzaDropdown.adapter = adapter
}
pizzaDialogBuilder.show()
}
项目目前在 strings.xml 资源文件中硬编码为字符串数组。
AlertDialog 出现了,我可以看到并点击下拉菜单的箭头,但是当我点击它时什么也没有发生。
解决方法
您正在对不包含 findViewById
的当前活动调用 R.id.pizza_selection
。因此我怀疑你会看到
val pizzaDropdown = findViewById<Spinner>(R.id.pizzaSelection)
返回null
。
尝试这样的事情:
// inflate your layout
val dialogView = LayoutInflater.from(this).inflate(R.layout.pizza_alert_dialog,null,false)
// and set it as dialog view
pizzaDialogBuilder.setView(dialogView)
// then call findViewById on this ViewGroup to get the Spinner
val pizzaDropdown = dialogView.findViewById<Spinner>(R.id.pizzaSelection)
我的 Kotlin 语法可能不正确,抱歉。重要的是我们在 findViewById
上调用 dialogView
,而不是隐含的 this.findViewById()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。