Search code examples
androidandroid-widgetandroid-spinnerandroid-background

Displaying the arrow of an Android spinner


I have a spinner, whose background is defined in a drawable file:

<style name="spinner_style" parent="android:Widget.Material.Light.Spinner">
    <item name="android:background">@drawable/background_spinner</item>
</style>

And the style:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/red" />
    <corners android:radius="3dp" />
</shape>

The problem is that the arrow isn't displayed. It's due to: <item name="android:background">@drawable/background_spinner</item>.

How could I add it, for example within the drawable file?


Solution

  • Solution:

    You should define an <layer-list> to do so:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item>
            <layer-list>
    
                <item>
                    <shape>
                        <gradient android:angle="90" android:endColor="#ffffff" android:startColor="#ffffff" android:type="linear" />
                        <stroke android:width="0.33dp" android:color="#0fb1fa" />
                        <corners android:radius="0dp" />
                        <padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp" />
                    </shape>
                </item>
    
                <item android:right="5dp">
                    <bitmap android:gravity="center_vertical|right" android:src="@drawable/arrow_down_gray" />
                </item>
    
            </layer-list>
    
        </item>
    </selector>
    

    Then, replace the line: android:src="@drawable/arrow_down_gray" with your arrow drawable.

    Finally, apply this as your style="@style/spinner_style" in your spinner.

    Explaination: <layer-list> info can be found here: https://developer.android.com/guide/topics/resources/drawable-resource#LayerList and <bitmap> are used to draw an image on the screen. We choose the drawable image and set the gravity.

    More info on this may be other senior experts can provide you.

    Hope it helps.