'How to center spinner items using styles.xml?

How to center spinner items through styles without creating custom item view? Without extra work in code, just using styles.

enter image description here



Solution 1:[1]

We need to set these styles for spinner and its dropdown:

<style name="AppTheme" parent="Theme.MaterialComponents.NoActionBar">
    <!-- Our app (or activity) theme. Here we set custom styles for spinner and its dropdown -->
    <item name="spinnerStyle">@style/Spinner</item>
    <item name="spinnerDropDownItemStyle">@style/SpinnerDropDownItem</item>
</style>

<style name="Spinner" parent="Widget.AppCompat.Spinner">
    <!-- Optional: Remove annoying triangle -->
    <item name="android:background">@null</item>
    <!-- Optional: Adding ripple effect -->
    <item name="android:foreground">?attr/selectableItemBackgroundBorderless</item>
    <!-- Centering text in spinner -->
    <item name="android:textAlignment">center</item>
</style>

<style name="SpinnerDropDownItem" parent="Widget.AppCompat.TextView.SpinnerItem">
    <!-- Centering text in spinner dropdown -->
    <item name="android:gravity">center</item>
    <item name="android:textAlignment">center</item>
</style>

Result:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mikhail