2010-06-02 53 views
6

我試圖獲得EditText的字符數。我查看了EditText和TextView類的不同屬性,但似乎沒有返回字符數量的函數。我曾嘗試使用TextWatcher,但這並不理想,因爲有時我會根據首選項將已保存的消息加載到EditText中,並且TextWatcher不會計算未正確鍵入的字符。獲取EditText的字符數

任何幫助將是偉大的!

乾杯!

+0

我知道它已經被解答。但它可能有助於其他人。你也可以使用editText.length() – FaisalAhmed 2017-11-08 08:21:28

回答

23

只要抓住中的EditText文本作爲一個字符串,並檢查它的長度:

int length = editText.getText().length(); 
+0

太棒了,但我們怎麼才能顯示TextView恰好在edittext的正下方,並且在用戶輸入時應該可見。我們知道在鍵盤和編輯文本之間沒有顯示任何空間。謝謝。 – 2015-01-08 07:23:15

10
EditText edittext; 
private final TextWatcher mTextEditorWatcher = new TextWatcher() { 

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

     } 

     public void onTextChanged(CharSequence s, int start, int before, int count) { 
      //This sets a textview to the current length 
      textview.setText(String.valueOf(s.length()); 
     } 

     public void afterTextChanged(Editable s) { 
     } 
}; 
editText.addTextChangedListener(mTextEditorWatcher); 
+0

你只需要獲取EditText就可以得到它的文本爲String並獲取該字符串的長度。 – 2013-03-14 19:01:10

+0

這不是打火。 – 2015-03-05 05:15:45