Spinner onitemclicklistener无法正常工作

时间:2014-01-04 06:05:16

标签: android spinner android-spinner onclicklistener onitemclicklistener

我的应用程序中有一个Spinner,单击某个项目时它不起作用。我得到了值,但if条件没有得到解决。

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                Object item = parent.getItemAtPosition(pos);

                String Text = effecttwo.getSelectedItem().toString();
                System.out.println("spinner is -"+item+"-");

// I get the correct values in System.out.println

                if(Text=="Hue"){

           // not entering into this condition or any other condition       

                }else if(Text=="Saturation"){


                }else if(Text=="Brightness"){



                }else{

                }


            }
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

请告诉我我做错了什么。

3 个答案:

答案 0 :(得分:2)

I get the values but the if condition is not getting worked.

if(Text=="Hue"){

错误

使用.equals.equalsIgnoreCase来比较字符串

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals(java.lang.Object)

if(Text.equals("Hue"))
{

}

What is the difference between == vs equals() in Java?

答案 1 :(得分:1)

您不要将字符串与==进行比较。使用此:

if(text.equals("Hue"))
{

}

所以你的代码是这样的:

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            Object item = parent.getItemAtPosition(pos);

            String Text = effecttwo.getSelectedItem().toString();
            System.out.println("spinner is -"+item+"-");

// I get the correct values in System.out.println

            if(text.equals("Hue")){

       // not entering into this condition or any other condition       

            }else if(text.equals("Saturation")){


            }else if(text.equals("Brightness")){



            }else{

            }


        }
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

答案 2 :(得分:1)

不要在匿名类中执行侦听器。

使用spinner.setOnItemSelectedListener(this)执行此操作,并将implement AdapterView.OnItemSelectedListener放在您的片段或活动之后。