我正在尝试在ImageView上使用switch语句并分配一个String值,因此在我的onClick函数中,我可以根据单击的ImageView执行某些功能,并根据单击的ImageView使用String值。很抱歉有不好的解释,下面是代码示例。
ChooseLevelActivity.java
public class ChooseLevelActivity extends Activity implements View.OnClickListener {
ImageView level001, level002, level003, level004, level005;
String level_selected;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choose_level);
level001 = (ImageView) findViewById(R.id.level001);
level002 = (ImageView) findViewById(R.id.level002);
level003 = (ImageView) findViewById(R.id.level003);
level004 = (ImageView) findViewById(R.id.level004);
level005 = (ImageView) findViewById(R.id.level005);
// Array of ImageView
final ImageView[] levelsArray = {level001, level002, level003, level004, level005};
for(int i = 0; i < 5; i++) {
levelsArray[i].setOnClickListener(this);
}
}
@Override
public void onClick(View v) {
/* Switch statement to change the value of String level_selected
* depending on which ImageView is clicked.
* but an error "Constant expression required" shows up
* What am I missing? How to use the switch on ImageView ?
*/
switch (v) {
case level001:
level_selected = "level001";
break;
case level002:
level_selected = "level002";
break;
}
// Some function that uses the String level_selected
}
}
答案 0 :(得分:1)
为什么不使用已经不变的View的id
,而不是比较v本身?
switch (v.getId()) {
case R.id.level001:
level_selected = "level001";
break;
case R.id.level002:
level_selected = "level002";
break;
}