2012-09-28 13 views
5

私は簡単な質問があります。edittextの最後の文字を削除します。

私はいくつかの番号の画面を持っていますが、数字の1つをクリックすると、数字が編集テキストの最後に追加されます。

input.append(number); 

私はまた、ユーザが、私は最後の文字を削除するには、このボタンをクリックすると、戻るボタンを持っています。私は、次のしている瞬間に

Editable currentText = input.getText(); 

if (currentText.length() > 0) { 
    currentText.delete(currentText.length() - 1, 
      currentText.length()); 
    input.setText(currentText); 
} 

は、これを行うための簡単な方法はありますか? input.remove()の行に何か?

+1

私は、これは単純ではありませんし、しません – njzk2

答えて

10

は、私は、これは古い質問ですが、それはまだ有効だ実現しています。テキストを自分でトリムすると、setText()を実行するとカーソルが開始位置にリセットされます。だからではなく、(njzk2で述べたように)、キーイベントを削除し、プラットフォームがあなたのためにそれを処理させる偽の送信...

//get a reference to both your backButton and editText field 

EditText editText = (EditText) layout.findViewById(R.id.text); 
ImageButton backButton = (ImageButton) layout.findViewById(R.id.back_button); 

//then get a BaseInputConnection associated with the editText field 

BaseInputConnection textFieldInputConnection = new BaseInputConnection(editText, true); 

//then in the onClick listener for the backButton, send the fake delete key 

backButton.setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     textFieldInputConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL)); 
    } 
}); 
+2

良いアプローチで、機能している!注意すべき点の1つは、コード*は「削除」キーを押すことをシミュレートするだけです。削除が機能するには、 'EditText'にフォーカスがなければなりません。 'editText.isFocused()'を使って確認し、 'editText.requestFocus()'を使ってフォーカスを合わせることができます。また、最後にカーソルを置くので、最後の文字が削除されます。 –

8

これを試してみて、

String str = yourEditText.getText().toString().trim(); 


    if(str.length()!=0){ 
    str = str.substring(0, str.length() - 1); 

    yourEditText.setText (str); 
} 
+3

内部デルキーでのKeyEventを注入します境界をチェックする。 – njzk2

+0

これは編集テキストの先頭にカーソルを置くが、これは理想的ではない –

関連する問題