How to remove the last character from TextView in Android?
本问题已经有最佳答案,请猛点这里访问。
我正在为一个班级创建一个计算器应用程序,除了"退格键"按钮,我所有的东西都在工作。在操作textView时,我能找到的唯一信息是使用settext方法将textView重置为空或仅为空字符串。不过,我需要做的是删除最后一个输入到计算器中的数字,例如:如果输入数字12并按下退格键,它将删除2,但保留1。我决定只包括我的"onclick"方法,因为它是唯一与这个问题相关的方法。所有的计算都是用另一种方法完成的。谢谢!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | 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; } } |
使用子字符串
它将允许您按索引替换/删除字符(在您的情况下,它将是字符串的最后一个索引)
1 | NumberEntered = NumberEntered.substring(0, NumberEntered.length() - 1); |
如果您输入的号码是1829384
长度为7,索引将从0开始
当子串时,它将从0到(7-1),因此新串将为182938。