简体   繁体   中英

How to use the selected item of a spinner in an if statement (Android in eclipse)

Hi I have a spinner (spinner5) and whenever the user selects an item that says "age" I want the textview to change to 21. I have tried the following but it doesnt work. I can do this by using if (getSelectedItemPosition() == 1) but the spinner's contents are dynamic so thats not an option.

            if (spinner5.getSelectedItem().toString()=="age"){
            textArea.setText("21");
        }

Always Use .equals when compare two string because == only use for Primitive data types

.equals =compare two string value == =compare two string refrences

if (spinner5.getSelectedItem().toString().equals("age")){
            textArea.setText("21");
        }

Well assuming that your Item's toString() method is returning "age", then you need to do a string comparison instead of a ==. In Java, operators can't be overloaded, so == compares the actual object references as opposed to the contents. What you're looking for is:

spinner5.getSelectedItem().toString().equals("age")

as a rule, always use .equals() unless your type is a primitive, like int, float, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM