Skip to content
Advertisement

Displaying Error if no item from a AutoCompleteTextView is selected

I want to show an error message if no item is selected from the AutoCompleteTextView.

Here is my XML

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/customerSpinnerLayout"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="10dp"
            android:layout_marginRight="20dp"
            android:hint="Gender"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textInputLayout3"
            app:startIconDrawable="@drawable/ic_gender">

            <androidx.appcompat.widget.AppCompatAutoCompleteTextView
                android:id="@+id/spinnerGender"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:clickable="true"
                android:inputType="none"
                android:focusable="false"
                tools:ignore="KeyboardInaccessibleWidget,SpeakableTextPresentCheck" />
        </com.google.android.material.textfield.TextInputLayout>

Java Code

    ArrayAdapter<CharSequence> genderAdapter = ArrayAdapter.createFromResource(this,
            R.array.gender,
            android.R.layout.simple_spinner_item);
    genderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerGender.setAdapter(genderAdapter);


    String gender = spinnerGender.getText().toString();

    if (gender.isEmpty()){
        spinnerGender.setError("Select your gender");
        spinnerGender.requestFocus();
    }

It is not working What am I doing wrong?

enter image description here

Advertisement

Answer

If I set an error on customerSpinnerLayout then it works

Everything is the same as above you just have to change the condition

    if (gender.isEmpty()){
        customerSpinnerLayout.setError("Select your gender");
        // you can also requestFocus
    }

It works for me. Best of luck

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement