How do you set the max number of characters for an

2019-01-30 09:16发布

How do you set the max number of characters for an Android EditText input? I see setMaxLines, setMaxEMS, but nothing for the number of characters.

8条回答
再贱就再见
2楼-- · 2019-01-30 09:53

You can use a InputFilter, that's the way:

EditText myEditText = (EditText) findViewById(R.id.editText1);
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter.LengthFilter(10); //Filter to 10 characters
myEditText .setFilters(filters);
查看更多
在下西门庆
3楼-- · 2019-01-30 09:58

Dynamically:

editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(MAX_NUM) });

Via xml:

<EditText
    android:maxLength="@integer/max_length"
查看更多
霸刀☆藐视天下
4楼-- · 2019-01-30 10:06
   <EditText
        android:id="@+id/edtName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter device name"
        android:maxLength="10"
        android:inputType="textFilter"
        android:singleLine="true"/>

InputType has to set "textFilter"

        android:inputType="textFilter"
查看更多
别忘想泡老子
5楼-- · 2019-01-30 10:10

In XML you can add this line to the EditText View where 140 is the maximum number of characters:

android:maxLength="140"
查看更多
做个烂人
6楼-- · 2019-01-30 10:13

It worked for me this way, it's the best I've found. It is for a max length of 200 characters

editObservations.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (editObservations.getText().length() >= 201){
                String str = editObservations.getText().toString().substring(0, 200);
                editObservations.setText(str);
                editObservations.setSelection(str.length());
        }
    }

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

    @Override
    public void afterTextChanged(Editable s) {
    }
});
查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-01-30 10:14

I always set the max like this:

    <EditText
        android:id="@+id/edit_blaze_it
        android:layout_width="0dp"
        android:layout_height="@dimen/too_high"

    <!-- This is the line you need to write to set the max-->
        android:maxLength="420"
        />
查看更多
登录 后发表回答