EditText實時監聽輸入多少個字
阿新 • • 發佈:2019-01-27
不廢話,直接上程式碼,都是基礎,基本能看的懂,直接複製貼上即可使用;
介面佈局:
<LinearLayout android:layout_width="match_parent" android:layout_height="100dp" android:layout_marginRight="20dp" android:background="@drawable/edit_bt" android:orientation="vertical" android:paddingTop="5dp"> <EditText android:id="@+id/ed_cooperation_introduce" style="@style/help_layout" android:layout_width="match_parent" android:layout_height="80dp" android:background="@null" android:gravity="left|top" android:hint="請用文字簡單描述您的合作內容(100字內)" android:padding="5dp" android:textSize="12sp" /> <TextView android:id="@+id/tv_cooperation_hin" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="right" android:paddingRight="5dp" android:text="100" android:textSize="12sp" /> </LinearLayout>
oncreate程式碼;
//顯示輸入字元數量 showCharNumber(100); //判斷etContent.gettext()是否為空 if (TextUtils.isEmpty(binding.edCooperationIntroduce.getText().toString())) { binding.tvCooperationHin.setText("100"); } else { int ed_lenght = binding.edCooperationIntroduce.getText().length(); int lenght = 100 - ed_lenght; binding.tvCooperationHin.setText(String.valueOf(lenght)); }
private void showCharNumber(final int maxNumber) { binding.edCooperationIntroduce.addTextChangedListener(new TextWatcher() { private CharSequence temp; private int selectionStart; private int selectionEnd; @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { temp = s; } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { int number = s.length(); int lenght = 100 - number; // tv_size.setText(number + "/" + maxNumber); binding.tvCooperationHin.setText(String.valueOf(lenght)); selectionStart = binding.edCooperationIntroduce.getSelectionStart(); selectionEnd = binding.edCooperationIntroduce.getSelectionEnd(); //System.out.println("start="+selectionStart+",end="+selectionEnd); if (temp.length() > maxNumber) { s.delete(selectionStart - 1, selectionEnd); int tempSelection = selectionStart; binding.edCooperationIntroduce.setText(s); binding.edCooperationIntroduce.setSelection(tempSelection); toast("最多100字"); } } }); }