我有一个带有微调器下拉菜单的应用程序。当我从微调器下拉菜单中点击Admin时,它不会转到Admin.class。和教师一样,当我从微调器下拉菜单中点击教师时,它不会转到Student.class。\
我的代码:
public class Home extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
String[] sp1 = getResources().getStringArray(R.array.Level);
Spinner spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,sp1);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String s = parent.getItemAtPosition(position).toString();
if(s=="Admin")
startActivity(new Intent(Home.this,Admin.class));
if(s=="Teacher")
startActivity(new Intent(Home.this,Student.class));
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
答案 0 :(得分:1)
使用firstString.equals(secondString)
函数比较字符串,而不是==
运算符。
该函数检查字符串的实际内容,==
运算符检查对象的引用是否相等。请注意,字符串常量通常是“实例化”,这样两个具有相同值的常量实际上可以与==
进行比较,但最好不要依赖它。
这样做
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String s = parent.getItemAtPosition(position).toString();
if(s.equals("Admin"))
startActivity(new Intent(Home.this,Admin.class));
if(s.equals("Teacher"))
startActivity(new Intent(Home.this,Student.class));
}
修改强>
public class Home extends Activity {
private boolean spinnerAutoSelectionDone = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
String[] sp1 = getResources().getStringArray(R.array.Level);
Spinner spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,sp1);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(!spinnerAutoSelectionDone){
spinnerAutoSelectionDone = true;
return;
}
String s = parent.getItemAtPosition(position).toString();
if(s.equals("Admin"))
startActivity(new Intent(Home.this,Admin.class));
if(s.equals("Teacher"))
startActivity(new Intent(Home.this,Student.class));
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
答案 1 :(得分:1)
uses.equals()方法而不是==运算符.... 因为你在这里比较参考而不是价值。