我试图要求用户在创建帐户之前在微调器中选择一个项目。所以我正在检查是否使用if语句选择了一个项目。如果未选中,我会向用户显示一条零食消息,告诉他们必须选择一项。下面是代码:
val hearAboutUs =
if (utmSourcesSpinner.selectedIndex > 0) 1
else 0
if (hearAboutUs == 0) {
showErrorSnack("You must select where you heard about us.")
}
现在,当选择微调器中的第一项时,如果(utmSourcesSpinner.selectedIndex> 0)1否则0返回false,而如果选择了其余项,则如果(utmSourcesSpinner.selectedIndex> 0)1否则0返回true。
Spinner.selectedIndex返回所选项目的第一个所选项目的索引是位置0,所以0不是> 0所有的Spinners首先都选择了0索引,因此您不需要对其进行验证
spinner.getSelectedItemPosition()返回所选项目的索引。
int pos = spinner.getSelectedItemPosition();
if (pos > 0) {
// spinner option is selected
} else {
//show toast please select item.
}