I’m using MaterialAutoCompleteTextView to display a dropdown list for selecting a theme.
xml:
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/chooseThemeContainer"
style="@style/ChooseThemeInputLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:hint="@string/theme"
android:textColorHint="@color/textLink"
app:endIconTint="@color/textLink"
app:layout_constraintEnd_toStartOf="@id/saveName"
app:layout_constraintStart_toStartOf="@id/avatar"
app:layout_constraintTop_toBottomOf="@id/avatar">
<com.google.android.material.textfield.MaterialAutoCompleteTextView
android:id="@+id/chooseTheme"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawableTint="@color/textLink"
android:inputType="none"
android:textColorHint="@color/textLink"
android:textColor="@color/textLink"/>
</com.google.android.material.textfield.TextInputLayout>
in the fragment’s onViewCreated method call initChangeThemeEditText():
private fun initChangeThemeEditText() {
viewModel.themeItems.observe(viewLifecycleOwner) { items ->
binding.chooseTheme.setSimpleItems(items)
val selectedIndex = when (themeController.themeType) {
ThemeController.ThemeType.AS_SYSTEM -> 0
ThemeController.ThemeType.DAY -> 1
ThemeController.ThemeType.NIGHT -> 2
}
binding.chooseTheme.setText(items[selectedIndex], false)
}
}
themeController reads and writes the value of the installed theme to the database through the repository
from viewModel I get a list of strings:
private val _themeItems = MutableLiveData<Array<String>>()
val themeItems: LiveData<Array<String>> = _themeItems
init {
val items = arrayOf(
resourceProvider.getString(stringResources.theme_as_system),
resourceProvider.getString(stringResources.theme_day),
resourceProvider.getString(stringResources.theme_night)
)
_themeItems.value = items
}
On initial boot everything goes well. The saved value is correctly set to MaterialAutoCompleteTextView.
Next, in the selection listener, the theme changes if necessary.
And, it turns out, the fragment and its views are recreated.
And MaterialAutoCompleteTextView is displayed with the list open.
Setting binding.chooseTheme.dismissDropDown() after setText() had no effect.
I tried all the solutions from here.
The only thing that works is:
...
binding.chooseTheme.setText(items[selectedIndex], false)
binding.chooseTheme.postDelayed(50) {
binding.chooseTheme.dismissDropDown()
}
But this solution does not make me happy and is visible on the user interface.
Is there a normal way to force MaterialAutoCompleteTextView not to open the list after being recreated?