如何在Android中设置EditText的最大字符数?

如何设置Android EditText输入的最大字符数? 我看到setMaxLines,setMaxEMS,但没有任何字符数。

8个解决方案

233 votes

在XML中,您可以将此行添加到EditText View,其中140是最大字符数:

android:maxLength="140"

Massimo Variolo answered 2019-07-05T22:06:48Z

47 votes

动态:

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

通过xml:

android:maxLength="@integer/max_edittext_length"

goRGon answered 2019-07-05T22:07:18Z

44 votes

您可以使用InputFilter,方式如下:

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);

Superlandero answered 2019-07-05T22:07:41Z

10 votes

这可能有所帮助:

[http://www.tutorialforandroid.com/2009/02/maxlength-in-edittext-using-codes.html]

[http://www.anddev.org/edit_text_max_limit_charactars-t1925.html]

no.good.at.coding answered 2019-07-05T22:08:19Z

6 votes

我总是像这样设置最大值:

android:id="@+id/edit_blaze_it

android:layout_width="0dp"

android:layout_height="@dimen/too_high"

android:maxLength="420"

/>

ZooMagic answered 2019-07-05T22:08:42Z

3 votes

它对我有用。

etMsgDescription.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maximum_character)});

etMsgDescription.addTextChangedListener(new TextWatcher() {

@Override

public void onTextChanged(CharSequence s, int start, int before, int count) {

tvCharacterLimite.setText(" "+String.valueOf(maximum_character - etMsgDescription.getText().length()));

}

@Override

public void beforeTextChanged(CharSequence s, int start, int count,

int after) {

// TODO Auto-generated method stub

}

@Override

public void afterTextChanged(Editable s) {

// TODO Auto-generated method stub

}

});

Chirag answered 2019-07-05T22:09:06Z

0 votes

它以这种方式对我有用,它是我发现的最好的。它的最大长度为200个字符

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) {

}

});

Camilo Soto answered 2019-07-05T22:09:30Z

0 votes

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必须设置" textFilter"

android:inputType="textFilter"

Shetty Suresh Babu. answered 2019-07-05T22:09:54Z

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐