java 如何在 Android 中获取 Spinner 选定项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17129021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:04:46  来源:igfitidea点击:

How to get Spinner Selected Item in Android

javaandroidspinner

提问by Rohodude

I am making a currency converter with two spinners. I want to make an "if" function using the values of the spinner's selected item like below.

我正在制作一个带有两个微调器的货币转换器。我想使用如下所示的微调器所选项目的值创建一个“if”函数。

    @Override
    public void onClick(View v) {
        if (spinner1.getSelectedItem()=="Dollars" && spinner2.getSelectedItem()=="Euros") {
            convertDollarstoEuros();
        }
        if (spinner1.getSelectedItem()=="Euros" && spinner2.getSelectedItem()=="Euros") {
            convertEurostoEuros();
        }
    Toast.makeText(MainActivity.this,
            "OnClickListener : " + 
                    "\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) + 
                    "\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
                Toast.LENGTH_SHORT).show();
        }

The problem is that the toast is showing, but the currencies aren't converting. The toast part is working, but the spinner part isn't. Any help would be greatly appreciated. Here is my LogCat:

问题是吐司正在显示,但货币没有转换。吐司部分正在工作,但微调部分没有。任何帮助将不胜感激。这是我的 LogCat:

enter image description here

在此处输入图片说明

回答by Gauthier Boaglio

Try this :

试试这个 :

if (spinner1.getSelectedItem().toString().equals("Dollars") && spinner2.getSelectedItem().toString().equals("Euros")
...

getSelectedItem() returns an Object. info. So you have to get the corresponding string first. Then java compares strings using equals().

getSelectedItem() 返回一个Object. 信息。所以你必须先得到对应的字符串。然后 java 使用equals().

回答by Ahmad

if (spinner1.getSelectedItem()=="Dollars" && spinner2.getSelectedItem()=="Euros") {

You can't compare Strings like that. You have to use the equals()method to compare them. Use this:

你不能这样比较字符串。您必须使用该equals()方法来比较它们。用这个:

if (spinner1.getSelectedItem().toString().equals("Dollars") && spinner2.getSelectedItem().toString().equals("Euros")) {}

回答by Vinay Ganesh

Check whether you called the id correctly or not? When I was working when improper id was called this exception used to arise. For eg In TextView, findViewById(R.id.textView1) but in xml file we may have set it to textView2.

检查您是否正确调用了 id?当我在工作时调用了不正确的 id,这个异常曾经出现过。例如,在 TextView 中,findViewById(R.id.textView1) 但在 xml 文件中,我们可能已将其设置为 textView2。