【问题标题】:How to use the selected item of a spinner in an if statement (Android in eclipse)如何在 if 语句中使用微调器的选定项(Eclipse 中的 Android)
【发布时间】:2012-04-03 15:24:25
【问题描述】:
您好,我有一个微调器 (spinner5),每当用户选择一个显示“年龄”的项目时,我希望 textview 更改为 21。我尝试了以下方法,但它不起作用。我可以使用 if (getSelectedItemPosition() == 1) 来做到这一点,但微调器的内容是动态的,所以这不是一个选项。
if (spinner5.getSelectedItem().toString()=="age"){
textArea.setText("21");
}
【问题讨论】:
标签:
java
android
arrays
eclipse
spinner
【解决方案1】:
比较两个字符串时始终使用.equals,因为== 仅用于Primitive data types
.equals=比较两个字符串值
== =比较两个字符串引用
if (spinner5.getSelectedItem().toString().equals("age")){
textArea.setText("21");
}
【解决方案2】:
假设您的 Item 的 toString() 方法返回“年龄”,那么您需要进行字符串比较而不是 ==。在 Java 中,运算符不能重载,因此 == 比较实际的对象引用而不是内容。您正在寻找的是:
spinner5.getSelectedItem().toString().equals("age")
通常,除非您的类型是原始类型,如 int、float 等,否则请始终使用 .equals()。