2015-09-22 134 views
1

我正在爲一個班級創建一個計算器應用程序,除了「BackSpace」按鈕之外,我有一切工作。關於操作TextView的唯一信息是使用SetText方法將TextView重置爲null或只是一個空字符串。我需要做的是除去輸入到計算器前的最後一個數字:如果輸入數字12並按下退格鍵,它將刪除2,但離開1.我決定只包含我的「onClick」方法作爲與此問題相關的唯一方法,所有計算均以另一種方法完成。謝謝!如何從Android中的TextView中刪除最後一個字符?

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; 
     } 
    } 

回答

5

使用Substring

它可以讓你替換/被索引中刪除字符(在你的情況下,將字符串的最後一個索引)

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

如果你有多個輸入1829384

長度爲7,索引將從0開始

當substringed它將從0到(7-1),因此新的字符串將是182938

+0

我考慮使用子字符串方法,但我認爲你需要知道你在尋找什麼數字來工作。我試試這個試試謝謝你! –

+0

這樣做感謝現在似乎是一個愚蠢的問題。 –

+0

沒有。很高興知道它工作:) –

相關問題