如何从Android中的TextView中删除最后一个字符?

时间:2015-09-22 17:33:29

标签: java android textview

我正在为一个班级创建一个计算器应用程序,除了" BackSpace"按钮。我在操作TextView时可以找到的唯一信息是使用SetText方法将TextView重置为null或只是一个空字符串。我需要做的是删除输入到计算器ex中的最后一个数字:如果输入数字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;
        }
    }

1 个答案:

答案 0 :(得分:7)

使用Substring

它允许你用索引替换/删除字符(在你的情况下,它将是字符串的最后一个索引)

NumberEntered = NumberEntered.substring(0, NumberEntered.length() - 1);

如果您输入的号码是1829384

长度为7,索引将从0开始

当收录时它将从0到(7-1)因此新字符串将是182938