美文网首页android技术收藏Android学习面试技巧
在Android library中不能使用switch-case

在Android library中不能使用switch-case

作者: 张明云 | 来源:发表于2014-12-26 11:58 被阅读17140次

原因分析

  当我们在Android依赖库中使用switch-case语句访问资源ID时会报如下图所示的错误,报的错误是case分支后面跟的参数必须是常数,换句话说出现这个问题的原因是Android library中生成的R.java中的资源ID不是常数:

library errorlibrary error

  打开library中的R.java,发现确实如此,每一个资源ID都没有被声明为final:

library R.javalibrary R.java

  但是当你打开你的主工程,在onClick、onItemClick等各种回调方法中是可以通过switch-case语句来访问资源ID的,因为在主工程的R.java中资源ID都被声明为了final常量。

  project中能够通过switch-case语句正常引用资源ID:

project rightproject right

  project中的R.java:

project R.javaproject R.java

解决方案

  既然是由于library的R.java中的资源ID不是常量引起的,我们可以在library中通过if-else-if条件语句来引用资源ID,这样就避免了这个错误:

library uselibrary use

参考资料:

  为了进一步了解问题的具体原因,在万能的StackOverflow上还真搜到了这个问题:

In a regular Android project, constants in the resource R class are declared like this:

public static final int main=0x7f030004;

However, as of ADT 14, in a library project, they will be declared like this:

public static int main=0x7f030004;

In other words, the constants are not final in a library project. Therefore your code would no longer compile.

The solution for this is simple: Convert the switch statement into an if-else statement.

public void onClick(View src)
{
int id = src.getId();
if (id == R.id.playbtn){
checkwificonnection();
} else if (id == R.id.stopbtn){
Log.d(TAG, "onClick: stopping srvice");
Playbutton.setImageResource(R.drawable.playbtn1);
Playbutton.setVisibility(0); //visible
Stopbutton.setVisibility(4); //invisible
stopService(new Intent(RakistaRadio.this,myservice.class));
clearstatusbar();
timer.cancel();
Title.setText(" ");
Artist.setText(" ");
} else if (id == R.id.btnmenu){
openOptionsMenu();
}
}
http://tools.android.com/tips/non-constant-fields

Tip
You can quickly convert a switch statement to an if-else statement using Eclipse's quick fix.

Click on the switch keyword and press Ctrl + 1 then select

Convert 'switch' to 'if-else'.

  问题详见:switch case statement error: case expressions must be constant expression

相关文章

网友评论

  • 牙Sir:赞一个~
  • denglxsc:刚好遇到这个问题,之前是一个项目里面的代码,我把它抽离成模块,结果就报错,当时还以为studio抽风了:grin:
  • 五香鱼cc:龙哥,了解为什么libaray的R资源是非final的吗
    SuperYFan:多个Library中可能出现id冲突的问题,为了解决这个问题谷歌将Library工程R文件才从静态常量变为非常量。
    望北8261:我也想知道为什么要这样设计
  • d3e4c22bb09b:好大的一个坑
  • 韦驮天:嘿嘿,还是写的不错的
  • BigLong:不错不错,刚好遇到这个问题。
  • granton_zhuang:虽然这个在Android studio里有很直接的提示,不过原理还是看了这篇文章才明白,感谢作者。
    其实Android studio的提示和建议解决方案能解决很多问题了。
    虽然一键就换成if else的模式很方便,但是我还是习惯用if 条件,执行完就return的写法。
    感觉大量else if的嵌套代码可读性反而降低了。

本文标题:在Android library中不能使用switch-case

本文链接:https://www.haomeiwen.com/subject/fqbatttx.html