这是一个二维码生成项目,这是代码源 That is the source 这里是常量情况的错误 我知道它必须放在 If-else 中,但我不知道在这个项目中任何人都可以帮助我?!
//That is a QR code generator project`enter code here`
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1://<--- is the error .. I can't make it If-else statement
EditText qrInput = (EditText) findViewById(R.id.QR);
String qrInputText = qrInput.getText().toString();
Log.v(LOG_TAG, qrInputText);
//Find screen size
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
int width = point.x;
int height = point.y;
int smallerDimension = width < height ? width : height;
smallerDimension = smallerDimension * 3/4;
//Encode with a QR Code image
QREncoder qrCodeEncoder = new QREncoder(qrInputText,
null,
Contents.Type.TEXT,
BarcodeFormat.QR_CODE.toString(),
smallerDimension);
try {
Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
ImageView myImage = (ImageView) findViewById(R.id.imageView1);
myImage.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
break;
// More buttons go here (if any) ...
}
}
}
最佳答案
看看关于这个的官方博文:
http://tools.android.com/recent/switchstatementconversion
http://tools.android.com/tips/non-constant-fields
基本上,库项目中的资源常量不再是“最终的”。来自 ADT 网站:
换句话说,库项目中的常量不是最终的。原因很简单:组合多个库项目时,字段的实际值(必须是唯一的)可能会发生冲突。在 ADT 14 之前,所有字段都是最终的,因此,所有库在使用时都必须将所有资源和相关的 Java 代码与主项目一起重新编译。这对性能不利,因为它使构建非常缓慢。它还阻止分发不包含源代码的库项目,限制库项目的使用范围。
所以如果你修复它会将开关转换为 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();
}
关于android - Switch - case 表达式必须是常量表达式,我不能做 if-else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17849566/