Android - Issue with custom Spinner background

2019-09-02 16:17发布

问题:

I'm trying to give a custom background to my spinner. I've downloaded the HTC sense spinner design (Cf. following pictures) with the 9 patch format.

I've created a new XML file with the following code inside:

    <?xml version="1.0" encoding="utf-8"?>

    <selector xmlns:android="http://schemas.android.com/apk/res/android">

         <item
             android:state_focused="true" 
             android:state_pressed="false" 
             android:drawable="@drawable/spinner_pressed" />

        <item
            android:state_focused="true" 
            android:state_pressed="true"
            android:drawable="@drawable/spinner_pressed" />

        <item
            android:state_focused="false" 
            android:state_pressed="true"
            android:drawable="@drawable/spinner_pressed" />

        <item
            android:drawable="@drawable/spinner_normal" />

    </selector>

And I've added a spinner to my layout with this code:

<Spinner
    android:id="@+id/my_spinner"
    android:layout_width="180dp"
    android:layout_height="50dp"
    android:layout_marginLeft="20dp"
    android:background="@drawable/custom_spinner" />

But whereas being correctly displayed, I got the following format:

Did I make something wrong?

I hope you'll can help me.

Regards.

V.

回答1:

The stretchable areas defined on your 9-patch seem wrong, and that is why your 9-patch are stretched like this. Have a look at Nine-patch docs and notice that the left-border defines what area should be stretched. I think you should also define a stretchable area below the "arrow" if you want the "arrow" to be centered.

If you do not know how to edit 9-patch you should use draw9patch it is included in the AndroidSDK/tools.