Android studio:错误: 需要常量表达式
将一个项目作为library,通过import Moudle导入一个新项目引用时,爆出这个错误:需要常量表达式,定位到switch。于是百度一下,解决方法为把switch case,改成if else,即:
switch (v.getId()) {// 点击了清除按钮case R.id.btn_clear:clear();break;// 点击了取消按钮case R.id.btn_cancel:break;// 点击了加、减、乘、除按钮case R.id.btn_plus:case R.id.btn_minus:case R.id.btn_multiply:case R.id.btn_divide:operator = inputText; // 运算符refreshText(showText + operator);break;// 点击了等号按钮case R.id.btn_equal:// 加减乘除四则运算double calculate_result = calculateFour();refreshOperate(String.valueOf(calculate_result));refreshText(showText + "=" + result);break;// 点击了开根号按钮case R.id.ib_sqrt:double sqrt_result = Math.sqrt(Double.parseDouble(firstNum));refreshOperate(String.valueOf(sqrt_result));refreshText(showText + "√=" + result);break;// 点击了求倒数按钮case R.id.btn_reciprocal:double reciprocal_result = 1.0 / Double.parseDouble(firstNum);refreshOperate(String.valueOf(reciprocal_result));refreshText(showText + "/=" + result);break;// 点击了其他按钮,包括数字和小数点default:// 上次的运算结果已经出来了if (result.length() > 0 && operator.equals("")) {clear();}// 无运算符,则继续拼接第一个操作数if (operator.equals("")) {firstNum = firstNum + inputText;} else {// 有运算符,则继续拼接第二个操作数secondNum = secondNum + inputText;}// 整数不需要前面的0if (showText.equals("0") && !inputText.equals(".")) {refreshText(inputText);} else {refreshText(showText + inputText);}break;}
改为:
@Overridepublic void onClick(View v) {String inputText;if(v.getId() == R.id.btn_sqrt){inputText = "厂";} else {inputText = ((TextView) v).getText().toString();}if (v.getId() == R.id.btn_clear){clear();} else if (v.getId() == R.id.btn_cancel) {} else if (v.getId() == R.id.btn_plus || v.getId() == R.id.btn_minus || v.getId() == R.id.btn_multiply || v.getId() == R.id.btn_divide) {operator = inputText;refreshText(showText + operator);} else if(v.getId() == R.id.btn_equal) {double calculate_result = calculateFour();refreshOperate(String.valueOf(calculate_result));refreshText(showText + "=" + result);} else if(v.getId() == R.id.btn_sqrt) {double sqrt_result = Math.sqrt(Double.parseDouble(firstNum));refreshOperate(String.valueOf(sqrt_result));refreshText(showText+"厂="+result);} else if(v.getId() == R.id.btn_reciprocal){double reciprocal_result = 1.0 / Double.parseDouble(firstNum);refreshOperate(String.valueOf(reciprocal_result));refreshText(showText+"/="+result);} else {if(result.length() > 0 && operator.equals("")){clear();}if(operator.equals("")){firstNum = firstNum + inputText;} else {secondNum = secondNum + inputText;}if(showText.equals("0") && !inputText.equals(".")){refreshText(inputText);} else {refreshText(showText+inputText);}}}
具体原因:http://tools.android.com/tips/non-constant-fields.