【问题标题】:Displaying Error if no item from a AutoCompleteTextView is selected如果未选择 AutoCompleteTextView 中的任何项目,则显示错误
【发布时间】:2022-02-05 03:27:25
【问题描述】:

如果没有从 AutoCompleteTextView 中选择任何项目,我想显示一条错误消息。

这是我的 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 代码

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

它不工作我做错了什么?

【问题讨论】:

    标签: java android android-studio spinner autocompletetextview


    【解决方案1】:

    如果我在 customerSpinnerLayout 上设置错误,那么它会起作用

    一切都和上面一样,你只需要改变条件

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

    它对我有用。祝你好运

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 2012-07-07
      相关资源
      最近更新 更多