我正在比较微调器中选定字符串值的字符串值。但是,即使我正在测试的字符串与微调器中的字符串值相同,它也总是返回 false。我测试了不同的方法,简化了条件,结果总是一样的。日志中打印的值和字符串是一样的,为什么总是返回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!");
}
关于android-spinner - 如何将字符串值与微调器中的字符串进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39918170/