所以我正在尝试编写一个包含两个微调器和一个按钮的活动,当选择两个微调器并按下它时,它将带你进入另一个活动。除了一个组合,它应该产生一个Toast,说你不能这样做。
无论如何,这是代码:
public void onClick(View v) {
String spinnerchoice1 = ("spinner1Value");
String spinnerchoice2 = ("spinner2Value");
if((spinnerchoice1.equals("Walking")) && (spinnerchoice2.equals("Hiking"))){
Toast.makeText(getBaseContext(), "I'm sorry, this is not possible.", Toast.LENGTH_LONG).show();
}else{
Intent i = new Intent(GetDirections.this.getApplicationContext(), DirectionDisplay.class);
i.putExtra("spinner1Value", transportSpinner.getSelectedItem().toString());
i.putExtra("spinner2Value", locationSpinner.getSelectedItem().toString());
GetDirections.this.startActivity(i);
}
}
谁能告诉我哪里出错?
由于
答案 0 :(得分:9)
您正在比较两个硬编码字符串,if条件永远不会执行。将代码更改为:
public void onClick(View v) {
String transport = transportSpinner.getSelectedItem().toString();
String location = locationSpinner.getSelectedItem().toString();
if ("Walking".equals(transport) && "Hiking".equals(location)) {
Toast.makeText(getBaseContext(), "I'm sorry, this is not possible.", Toast.LENGTH_LONG).show();
} else {
Intent i = new Intent(GetDirections.this.getApplicationContext(), DirectionDisplay.class);
i.putExtra("spinner1Value", transport);
i.putExtra("spinner2Value", location);
GetDirections.this.startActivity(i);
}
}
答案 1 :(得分:1)
如果这是您的实际代码,那么您的if永远不会评估为true,因为您将字符串设置为不是“Walking”和“Hiking”的值
这两行:
String spinnerchoice1 = ("spinner1Value");
String spinnerchoice2 = ("spinner2Value");
需要是这样的(假设你的微调器只包含String对象而不包含其他类型):
String spinnerchoice1 = transportSpinner.getSelectedItem().toString();
String spinnerchoice2 = locationSpinner.getSelectedItem().toString();