處理Edittext限制字數提示,以及回車換行功能。

首先是edittext佈局文件

    <EditText
        android:inputType="text"
        android:imeOptions="actionDone"
        android:id="@+id/ets"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

 

首先動態加上倆行代碼,爲了防止edittext輸入不換行問題:

ets.setHorizontallyScrolling(false);
ets.setMaxLines(Integer.MAX_VALUE);

然後我們定義輸入內容個數:

final int length = 40;

然後通過edittext輸入監聽:

        ets.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;
            private int editStart ;
            private int editEnd ;
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int after, int count) {
                temp = charSequence.toString().trim();
                if(temp.length()>0) {
                    numBefore=temp.length();//已經輸入的字符長度
                    numAfter=length-temp.length();
                    //最終顯示的字符數
                    tv_times.setText((numBefore)+"");
                    if (temp.length() > length){
                        Toast.makeText(MainActivity.this, "你輸入得字數超過限制", Toast.LENGTH_SHORT).show();
                    }
                }else {
                    //最終顯示的字符數
                    tv_times.setText("0");
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                try {
                    editStart = ets.getSelectionStart();//開始的字符位置
                    editEnd = ets.getSelectionEnd();//結束的字符位置
                    if (temp.length() >length) {
                        editable.delete(editStart-1, editEnd);//刪除
                        int tempSelection = editStart;
                        ets.removeTextChangedListener(this);
                        ets.setText(editable);
                        ets.addTextChangedListener(this);
                        ets.setSelection(tempSelection);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

ok,這樣實現了我們想要得效果咯。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章