如何使用 styles.xml 将微调项居中?

How to center spinner items using styles.xml?

如何在不创建自定义项视图的情况下通过样式使微调器项居中?无需额外的代码工作,只需使用样式。

我们需要为微调器及其下拉菜单设置这些样式:

<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>

结果: