android 輸入框 實時計算剩餘的輸入字元數(addTextChangedListener)
阿新 • • 發佈:2019-02-04
照例先上傳效果圖:
1 佈局檔案很簡單
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- >
- <EditText
- android:id="@+id/editText"
-
android:layout_width="fill_parent"
- android:layout_height="150dp"
- />
- <TextView
- android:id="@+id/textView_show"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="您還可以輸入"
- />
- </RelativeLayout>
2 Activity 程式碼
- 定義變數
-
private
- private TextView tv;
- int MAX_LENGTH = 500; //最大輸入字元數500
- int Rest_Length = MAX_LENGTH;
- oncreate中新增如下程式碼:
- et = (EditText) findViewById(R.id.editText);
- tv = (TextView) findViewById(R.id.textView_show);
-
tv.setText(Html.fromHtml("您還可以輸入:"
- et.addTextChangedListener(new TextWatcher() {
- @Override
- publicvoid onTextChanged(CharSequence s, int start, int before, int count) {
- // TODO Auto-generated method stub
- if(Rest_Length > 0){
- Rest_Length = MAX_LENGTH - et.getText().length();
- }
- }
- @Override
- publicvoid beforeTextChanged(CharSequence s, int start, int count,
- int after) {
- // TODO Auto-generated method stub
- tv.setText(Html.fromHtml("您還可以輸入:"+"<font color=\"red\">"+Rest_Length+"/500"+"</font>"));
- }
- @Override
- publicvoid afterTextChanged(Editable s) {
- // TODO Auto-generated method stub
- tv.setText(Html.fromHtml("您還可以輸入:"+"<font color=\"red\">"+Rest_Length+"/500"+"</font>"));
- }
- });