Android 正在验证微调器上的用户输入
我试图要求用户在创建帐户之前在微调器中选择一个项目。 因此,我使用if语句检查是否选中了一个项。如果没有选择,我会向用户显示一条零食信息,告诉他们必须选择一个项目。代码如下:Android 正在验证微调器上的用户输入,android,validation,kotlin,spinner,Android,Validation,Kotlin,Spinner,我试图要求用户在创建帐户之前在微调器中选择一个项目。 因此,我使用if语句检查是否选中了一个项。如果没有选择,我会向用户显示一条零食信息,告诉他们必须选择一个项目。代码如下: val hearAboutUs = if (utmSourcesSpinner.selectedIndex > 0) 1 else 0 if (hearAboutUs == 0) { showErrorSnack("You must select where you heard about us."
val hearAboutUs =
if (utmSourcesSpinner.selectedIndex > 0) 1
else 0
if (hearAboutUs == 0) {
showErrorSnack("You must select where you heard about us.")
}
现在,当微调器中的第一项被选中时,if(utmsourcespinner.selectedIndex>0)1 else 0返回false,而其余被选中的项if(utmsourcespinner.selectedIndex>0)1 else 0返回true Spinner.selectedIndex返回选定项在第一个位置的索引选定项是位置0,因此0不是>0所有微调器首先选择0索引,因此您不需要验证它Spinner.getSelectedItemPosition()返回选定项的索引
int pos = spinner.getSelectedItemPosition();
if (pos > 0) {
// spinner option is selected
} else {
//show toast please select item.
}
我就是这样处理这种情况的 “验证”按钮需要检查用户是否从微调器中选择了某些内容,默认情况下微调器有一个默认的选定项。此项的默认名称如下: “选择您听说我们的地点” 让我们开始吧
<Spinner
android:id="@+id/where"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginEnd="32dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
但我更喜欢为微调器创建一个objet表达式,基本上我创建了一个对象,该对象包含了类,我这样做,因为如果我们有4个微调器,我会更容易用对象表达式覆盖多次
override fun onItemSelected(parent: AdapterView<*>, view: View, pos: Int, id:Long) {
Log.d("test", "user select: ${where[pos]}")
Log.d("test", "user select: ${where.selectedItem}")
}
override fun onNothingSelected(parent: AdapterView<*>) {
// Another interface callback
}
}
在任何时刻,它都会保留选择项
参考资料:这是我用过的
spinner.setOnItemSelectedListener { _, _, _, item ->
mSelectedItem = item.toString()
}
if (mSelectedItem.isNullOrEmpty()) {
showErrorSnack("You must select where you heard about us")
}
我已将侦听器设置为微调器,然后我已检查所选项目是否为null或空,以显示消息“您必须选择您听说我们的地方”您可以从微调器的onItemSelected()获取位置,如果该位置为0,则提供其他信息以允许创建帐户。
where.selectedItem.text
spinner.setOnItemSelectedListener { _, _, _, item ->
mSelectedItem = item.toString()
}
if (mSelectedItem.isNullOrEmpty()) {
showErrorSnack("You must select where you heard about us")
}