Android: EditText maxLength being ignored

2019-06-05 03:49发布

I have a problem where this EditText ignores my maxLength completely.

<EditText
        android:id="@+id/dialog_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:inputType="numberPassword"
        android:maxLength="4"
        android:singleLine="true"
        android:textColorHint="@color/primary_lighter"
        android:textColor="@color/accent_harder"
        android:hint="****"
        />

maxLength is ignored

I can input how many characters I want.

This is a dialog and I cannot get the EditText by findViewById because its available programtaically when I press OK.

public void showNewQuestionDialog() {
    final AlertDialog.Builder builder = new AlertDialog.Builder( this );
    LayoutInflater inflater = this.getLayoutInflater();
    builder.setView( inflater.inflate( R.layout.dialog_question_new, null ) )
            .setPositiveButton( R.string.settings_ok, new  DialogInterface.OnClickListener() {
                @Override
                public void onClick( DialogInterface thisDialog, int id ) {
                    Dialog dialog2 = Dialog.class.cast( thisDialog );
                    EditText input = ( EditText ) dialog2.findViewById( R.id.dialog_input ); 

                    // Other code here..
                }
            } );
     .....

I solved it. The problem was this line:

        android:singleLine="true"

If you ever experience the same problem, try removing this line.

3条回答
我想做一个坏孩纸
2楼-- · 2019-06-05 04:10

I would make sure that your XML attributes are not effecting another one.

It seems like these 2 could be the issue

    android:maxLength="4"
    android:singleLine="true"

I see you solved it already! OK, the issue was...

    android:singleLine="true"

But you should double check to make sure that you cannot create a new line!

查看更多
放荡不羁爱自由
3楼-- · 2019-06-05 04:24

You need to remove below line in your layout to solve this problem

android:singleLine="true"

Apart from that, you can always inflate the EditText dynamically with custom view like below and you can register for textwatcher in input mode.

LayoutInflator mInflator = (LayoutInflater) context.getSystemService(Service.LAYOUT_INFLATER_SERVICE);
View view = mInflator.inflate(R.layout.dialog_question_new, null);
AlertDialog.Builder mBuilder = new AlertDialog.Builder(context, R.style.CustomDialogTheme);
EditText input = ( EditText ) view.findViewById( R.id.dialog_input_question_new); 
mBuilder.setCustomTitle(view);
mBuilder.setPositiveButton(...
mBuilder.setPositiveButton(...
查看更多
闹够了就滚
4楼-- · 2019-06-05 04:25

You could also use the underrated LengthFilter:

EditText editText = findViewById(R.id.edit_text);
int length = 4;
editText.setFilters(new android.text.InputFilter[] { new android.text.InputFilter.LengthFilter(length) });
查看更多
登录 后发表回答