如何将字符串值与微调器中的字符串进行比较?

How can I compare a string value with string from spinner?

我正在比较来自微调器的选定字符串值的字符串值。但是,即使我正在测试的字符串与微调器中的字符串值相同,它也总是 return false。我测试了不同的方法,简化了条件,结果总是一样的。 log中打印出来的值和字符串是一样的,为什么总是return false?

final Spinner spinner_familyTest = (Spinner) findViewById(R.id.spinner_family);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
        R.array.family_array, R.layout.spinner_layout);
    adapter.setDropDownViewResource(R.layout.spinner_layout);
    spinner_familyTest.setAdapter(adapter);

//  Value of familyTest from spinner as printed in the log is "Apiaceae"
    familyTest = spinner_familyTest.getSelectedItem().toString(); 

    if (familyTest == "Apiaceae") {
                    Log.i(TAG, "This is True!");
                    }
                    Log.i(TAG, "This is False");

前段时间我也遇到过同样的问题。诀窍是使用 equals() 而不是 ==

equals() compares string values whereas == compares string refrences

所以你需要做的是:

if (familyTest.equals("Apiaceae"))
{
   Log.i(TAG, "This is True!");
}