以前写代码是这样的:
int id = view.getId();
switch (id) {
case R.id.button1:
action1();
break;
case R.id.button2:
action2();
break;
case R.id.button3:
action3();
break;
}
但这次要以library形式嵌入,在打包的时候上面代码报错,编译不通过。
查阅文档才知道
Android项目中,R类的常量都是用final定义的,但ADT 14之后,如果在library 项目中,它会没有final关键字,
在switch语句的case中,如果使用 R.id.xxx 则会提示有问题,不允许非常量在case语句中。
Google提供的一个方法就是把它转化为if-else语句,即在switch语句处 Ctrl+1 然后可以替换成if-else.语句。
修改成后:
int id = view.getId();
if (id == R.id.button1) {
action1();
} else if (id == R.id.button2) {
action2();
} else if (id == R.id.button3) {
action3();
if (id == R.id.button1) {
action1();
} else if (id == R.id.button2) {
action2();
} else if (id == R.id.button3) {
action3();
}
编译通过就可以完成打包了。
地址: