简体   繁体   English

Android:错误-案例表达式必须是常量表达式

[英]Android:Error - Case expressions must be constant expressions

I have been working on an app, and recently got a new computer. 我一直在开发应用程序,最近又买了一台新计算机。 I had to import my existing code into this computer. 我必须将现有代码导入这台计算机。 Now, when I do this I get a few errors in the build path, so I fix them. 现在,当我这样做时,在构建路径中会遇到一些错误,因此我将其修复。 But now, I get errors in every case in my switch and case. 但是现在,我在各种情况下都遇到错误。 It says: case expressions must be constant expressions. 它说:case表达式必须是常量表达式。

An example of my code: 我的代码示例:

case R.id.b3:
    a.putExtra("Green", "green");
    startActivity(a);
    break;
case R.id.b4:
    a.putExtra("Pink", "pink");
    startActivity(a);
    break;

I get the errors on the ids of the button. 我收到按钮ID上的错误。 Everything worked fine on the other computer I used, so I'm not sure why I now get this error. 在我使用的另一台计算机上,一切正常,因此我不确定为什么现在会出现此错误。 I did google it and I read I should replace them all with an if else statement, but that would be a major pain to replace all my switch and cases, so I'd want to avoid that. 我用google搜索了,我读到我应该用if else语句替换它们,但是替换所有的switch和case会很麻烦,所以我想避免这种情况。

Why this happens on my imported code? 为什么在导入的代码上会发生这种情况?

This happens when your resources are defined in a library project. 当您的资源在库项目中定义时,就会发生这种情况。 I believe one of the newer versions of the Android plugin requires this based on changes to the way library projects are compiled. 我认为,Android插件的较新版本之一需要基于对库项目的编译方式进行更改的要求。 The if-else is necessary. if-else是必需的。 The IDE will do it for your automatically. IDE将自动为您执行此操作。 If you highlight the switch keyword and press ctrl-1 you should get an option to make the change automatically. 如果突出显示switch关键字并按ctrl-1,则应该有一个选项可以自动进行更改。

You can read about it here . 你可以在这里阅读。

Check the activity you are working with , the one that gives you the errors, and look up this line of code in it 检查您正在使用的活动(会给您带来错误的活动),并在其中查找这一行代码

import android.R;

delete it! 删除它! perform clean and everything should work 执行干净,一切都应该工作

自从ADT14 更改了工具链后不久以来,就没有保证id在库中是恒定的。

这可能是您正在使用third_party库,为了使您能够快速开发应用程序并能够使用多个库,资源ID未定义为final,因此您必须使用if / else而不是switch / case 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM