2013-03-26 38 views
2

我想在EditText中更改用戶輸入的字符。實際上,當用戶輸入編輯文本時,我想要的是,如果輸入字符是「S」,則用「B」字符替換它。我想要這樣做實時。更改用戶在Android中的EditText中輸入的字符

+0

你有什麼嘗試? – 2013-03-26 13:48:39

+0

您可以使用TextWatcher。 http://developer.android.com/reference/android/text/TextWatcher.html – Alex 2013-03-26 13:49:31

回答

7

我想在EditText中更改用戶輸入的字符。實際上當用戶輸入編輯文本時,我想要 ,如果輸入字符是「S」,用「B」字符替換它 。我想要這樣做實時。

最有可能你需要使用TextWatcher它非常適用於您的目標,並允許您在實時的EditText的內容來操作。

例子:

edittext.addTextChangedListener(new TextWatcher() { 

    public void onTextChanged(CharSequence s, int start, int before, int count) {   

    } 

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {  

    } 

    public void afterTextChanged(Editable s) { 

    } 
}); 
+0

你能給我一個真實的例子嗎?身份證你說什麼,但我不能得到我想要的。請使用 – Fcoder 2013-03-26 16:12:37

+0

@FarhadShirzad在google.com上使用textwatcher android例子。你可以開始[這裏](http://www.android-ever.com/2012/06/android-edittext-textwatcher-example.html) – Sajmon 2013-03-26 16:23:47

+0

@FarhadShirzad那麼如何?有用? – Sajmon 2013-03-26 18:40:39

0

使用

EditText textField = findViewById(R.id.textField); 
String text = textField.getText().toString(); 

那麼你可以使用之後

textField.setText(text,TextView.BufferType); 
text.replace('b','s'); 

TextView.BufferType可以有3個值表示here

0

像Sajmon解釋,你必須實現一個TextWatcher。你必須照顧光標。因爲用戶可以在現有文本字符串的任何位置輸入下一個字符(或剪貼板中的一個序列)。要處理這個問題,你必須在正確的位置改變字符(不要替換整個文本):

 damageEditLongText.addTextChangedListener(new TextWatcher() { 

     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, int after) {} 

     @Override 
     public void onTextChanged(CharSequence s, int start, int before, int count) {} 

     @Override 
     public void afterTextChanged(Editable s) { 
      // Nothing to replace 
      if (s.length() == 0) 
       return; 

      // Replace 'S' by 'B' 
      String text = s.toString(); 
      if (Pattern.matches(".*S.*", text)) { 
       int pos = text.indexOf("S"); 
       s.replace(pos, pos + 1, "B"); 
      } 
     } 
    }); 
相關問題