我正在为一个班级创建一个计算器应用程序,并且除“ BackSpace”按钮外,其他所有功能都可以正常工作。关于操作TextView的唯一信息是使用SetText方法将TextView重置为null或仅是一个空字符串。我需要做的是删除输入到计算器中的最后一个数字,例如:如果输入数字12并按退格键,它将删除数字2,但保留数字1。我决定只包括“ onClick”方法作为与此问题相关的唯一方法,所有计算都以另一种方法完成。谢谢!
public void onClick(View v) {
// display is assumed to be the TextView used for the Calculator display
String currDisplayValue = display.getText().toString();
Button b = (Button)v; // We assume only buttons have onClickListeners for this App
String label = b.getText().toString(); // read the label on the button clicked
switch (v.getId())
{
case R.id.clear:
calc.clear();
display.setText("");
//v.clear();
break;
case R.id.plus:
case R.id.minus:
case R.id.mult:
case R.id.div:
String operator = label;
display.setText("");
calc.update(operator, currDisplayValue);
break;
case R.id.equals:
display.setText(calc.equalsCalculation(currDisplayValue));
break;
case R.id.backSpace:
// Do whatever you need to do when the back space button is pressed
//Removes the right most character ex: if you had the number 12 and pressed this button
//it would remove the 2. Must take the existing string, remove the last character and
//pass the new string into the display.
display.setText(currDisplayValue);
break;
default:
// If the button isn't one of the above, it must be a digit
String digit = label;// This is the digit pressed
display.append(digit);
break;
}
}
使用子串
它将允许您按索引替换/删除字符(在您的情况下,它将是字符串的最后一个索引)
NumberEntered = NumberEntered.substring(0, NumberEntered.length() - 1);
如果输入了数字1829384
长度为7,索引将从0开始
子串化后,它的范围是0到(7-1),因此新的字符串是182938
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句