Проверка формы в Android TextInputLayout не работает правильно - PullRequest
1 голос
/ 27 марта 2019

Я пытаюсь проверить форму, я использую ошибку TextInputLayout, чтобы показать ошибку, когда я нажимаю кнопку «Отправить» в пустой форме, ошибка отображается только в поле «Имя», и ошибка не скрывается при заполнении имени текст. Также в других полях не отображается ошибка проверки.

activity_form.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:orientation="vertical">

        <android.support.design.widget.TextInputLayout
            android:id="@+id/nameTextInputLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.TextInputEditText
                android:id="@+id/formNameEdit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/form_hint_name"
                android:inputType="textPersonName"
                android:imeOptions="actionNext"
                android:maxLines="1" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/EmailTextInputLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.TextInputEditText
                android:id="@+id/formEmailEdit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/form_hint_email"
                android:inputType="textEmailAddress"
                android:imeOptions="actionNext"
                android:maxLines="1" />

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/PhoneTextInputLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/form_hint_mobile_number"
                android:imeOptions="actionNext"
                android:id="@+id/formMobileEdit"
                android:inputType="number"
                android:maxLines="1" />

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/AlternateTextInputLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/form_hint_alternate_number"
                android:imeOptions="actionNext"
                android:id="@+id/formAlternateEdit"
                android:inputType="number"
                android:maxLines="1" />

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/JEETextInputLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:imeOptions="actionNext"
                android:id="@+id/formJeeEdit"
                android:hint="@string/form_hint_jee"
                android:inputType="number"
                android:minLines="1" />

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/PercentageTextInputLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/form_hint_percentage"
                android:imeOptions="actionNext"
                android:id="@+id/formPerEdit"
                android:inputType="numberDecimal"
                android:minLines="1" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/CityTextInputLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:imeOptions="actionNext"
                android:hint="@string/form_hint_city"
                android:id="@+id/formCityEdit"
                android:inputType="text" />

        </android.support.design.widget.TextInputLayout>

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <Spinner
                android:id="@+id/deptSpinner"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                >

            </Spinner>

            <Spinner
                android:id="@+id/SourceSpinner"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content">
            </Spinner>


        </LinearLayout>

        <Button
            android:id="@+id/submit_btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/roundedbutton"
            android:text="@string/form_submit_btn" />
    </LinearLayout>

</ScrollView>

FormActivity.java

mSubmitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               Validation();
            }
        });

private void Validation(){
        boolean isValid = true;
        String dept = mDepartmentSpinner.getSelectedItem().toString();
        String source = mSourceSpinner.getSelectedItem().toString();

        String name = NameInputLayout.getEditText().getText().toString();

        if(NameInputLayout.getEditText().getText().toString().isEmpty()){
            NameInputLayout.setError("Enter Name");
            isValid = false;
        }else {
            NameInputLayout.setErrorEnabled(false);
            Log.d("form error", "Error removed");
        }
        String email = EmailInputLayout.getEditText().getText().toString();
        if(EmailInputLayout.getEditText().getText().toString().isEmpty()){
            NameInputLayout.setError("Enter Email");
            isValid = false;
        }else {
            NameInputLayout.setErrorEnabled(false);
        }

        String phone = PhoneInputLayout.getEditText().getText().toString().trim();
        if(phone.isEmpty()){
            NameInputLayout.setError("Enter Phone Number");
            isValid = false;
        }else {
            NameInputLayout.setErrorEnabled(false);
        }

        String alternate_num = AlternateInputLayout.getEditText().getText().toString();
        if(alternate_num.isEmpty()){
            NameInputLayout.setError("Enter Alternate Number");
            isValid = false;
        }else {
            NameInputLayout.setErrorEnabled(false);
        }

        String jee_marks = JeeInputLayout.getEditText().getText().toString();
        if(jee_marks.isEmpty()){
            NameInputLayout.setError("Enter Roll Number");
            isValid = false;
        }else {
            NameInputLayout.setErrorEnabled(false);
        }

        String percentage = PercentageInputLayout.getEditText().getText().toString();
        if(percentage.isEmpty()){
            NameInputLayout.setError("Enter Percentage");
            isValid = false;
        }else {
            NameInputLayout.setErrorEnabled(false);
        }

        String city = CityInputLayout.getEditText().getText().toString();
        if(city.isEmpty()){
            NameInputLayout.setError("Enter Name");
            isValid = false;
        }else {
            NameInputLayout.setErrorEnabled(false);
        }


        if(isValid){

            Boolean insert = dbHelper.insertForm(name,email,phone,alternate_num,jee_marks,percentage,city,dept,source);

            if(insert == true){

                Toast.makeText(getApplicationContext(),"Form Submitted",Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(FormActivity.this, MainActivity.class);
                startActivity(intent);

            }else {
                Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_SHORT).show();
            }

        }
}

Ответы [ 2 ]

1 голос
/ 27 марта 2019

здесь приведен фрагмент кода для удаления ошибки (прослушиватель изменения текста пользователя в тексте редактирования), который необходимо вызывать для каждого текста редактирования и макета ввода текста.

 public static void addTextChangedListener(EditText e, final TextInputLayout t) {
    e.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.length() > 0) {
                if (!TextUtils.isEmpty(t.getError())) {
                    t.setError(null);
                    t.setErrorEnabled(false);
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
}

и во-вторых, вы проверяете EmailInputLayout и устанавливаете ошибку дляNameInputLayout в каждом поле ввода.-скопировать вставить, но шустро.

0 голосов
/ 27 марта 2019

Кажется, вы используете один и тот же textInputlayout (NameInputLayout) со всеми вашими полями.Следовательно, после ввода имени, когда выполняется блок else, errorEnabled устанавливается в значение false, в результате чего другая ошибка не устанавливается.

И для устранения ошибки в вашем другом случае сделайте следующее: -

NameInputLayout.setError(null)

вместо: -

NameInputLayout.setErrorEnabled(false);

В противном случае вам придется установить для setErrorEnabled значение true, чтобы использовать его снова.

...