androidandroid-layoutmaterial-designautocompletetextview

Android - How to clear an ExposedDropdownMenu


I have an ExposedDropdownMenu like this:

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/input_layout_models"
    style="@style/Widget.Material3.TextInputLayout.FilledBox.ExposedDropdownMenu.Honk"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/size_medium"
   
 android:theme="@style/Widget.Material3.TextInputLayout.FilledBox.ExposedDropdownMenu.Honk"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/input_layout_brands">

        <AutoCompleteTextView
            android:id="@+id/auto_complete_text_models"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/vehicle_model"
            android:inputType="none"
            android:labelFor="@id/input_layout_models" />

</com.google.android.material.textfield.TextInputLayout>

And I fill it with elements like this:

private fun onModelsChanged(models: List<Model>) = binding.run {
    (autoCompleteTextModels as? MaterialAutoCompleteTextView)?.setSimpleItems(models
        .map { it.description }
        .toTypedArray()
    )
}

And I just want to clear its text. I tried the following:

1 Setting an empty list on my MaterialAutoCompleteTextView

(autoCompleteTextModels as? MaterialAutoCompleteTextView)?.setSimpleItems(
    emptyList<Model>().map { it.description }.toTypedArray()
)

2 Setting an empty text on my AutoCompleteTextView

autoCompleteTextModels.setText("")

3 Setting an empty text on my TextInputLayout

modelYearInput.setText("")

4 Clearing the editableText from my AutoCompleteTextView

(autoCompleteTextModels as? MaterialAutoCompleteTextView)?.editableText?.clear()

But nothing worked. Any idea on how I can achieve this?

I'm using this version of the Material Library:

implementation 'com.google.android.material:material:1.8.0'

Solution

  • I think you have some livedata, stateflow or similar altering your UI, because:

    This should clear the text on your AutoCompleteTextView:

    autoCompleteTextModels.setText("")
    

    This should clear it's list:

    (autoCompleteTextModels as? MaterialAutoCompleteTextView)?.setSimpleItems(emptyList()))
    

    One alternative by having a null adapter:

    autoCompleteTextModels.setAdapter(null)
    

    Another alternative with an empty list:

    (autoCompleteTextModels as? MaterialAutoCompleteTextView)?.setSimpleItems(
        emptyArray<String>()
            .map { it }
            .toTypedArray()
    )