How to create a Widget.Holo.Spinner-style widget i

2019-02-12 10:42发布

问题:

I have a Button that I want to style like a Holo-style spinner, i.e. underlined with a triangle in the bottom right corner - the built-in contacts app for example does that.

The easiest way is to create the button and style it as style="@android:style/Widget.Holo.Spinner" - that gives me the visual result I want.

However, my app is meant to support Android 2.x, so I can't use native Holo styles. AppCompat has several spinner-related styles, like @style/Widget.AppCompat.Spinner and others, but they don't look the same - they just create a little triangle in the center at the right edge of the widget, and no underline.

I could fudge it by creating my own 9-patch background, but I can't imagine that this Holo spinner style is missing from v7's AppCompat. Is there a style I can use, or any other way to create the visual result I want without creating my own drawable resource?

回答1:

I wouldn't recommend you to style a button like a spinner. Android have created a particular style for the button for a reason. THe reason behind this simple; you are going to confuse the users of your app if you style a button like a spinner, and they will think that the button is a spinner. That is why the Android design team do not recommend this.

Nonetheless, if you still wish to show the button as a sninner, you can always copy the design of the spinner, save it as an image and set it as the background of yuor button through this xml:

android:background="@drawable/spinner"

The spinner drawable needs to be saved in the drawables folder as an image.



回答2:

User "ozi" got me there, unfortunately his answer got deleted because it was just a link.

The trick is to use a custom attribute and override it with a v11-specific section. Here's the basic setup if you use themes:

In values/attr.xml:

<declare-styleable name="MyApp">
    <attr name="holoSpinnerStyle" format="reference" />
</declare-styleable>

You create your Spinner-Button like this:

<Button
    style="?attr/holoSpinnerStyle"
     />

And here's the key: You have different values in the theme depending on whether or not you have v11:

In values/themes.xml:

<style name="MyTheme">
    <item name="holoSpinnerStyle">@style/Widget.AppCompat.Spinner</item>
</style>

In values-v11/themes.xml:

<style name="MyTheme">
    <item name="holoSpinnerStyle">@android:style/Widget.Holo.Light.Spinner</item>
</style>

If you don't use themes, your setup is almost identical - you just use styles.xml, create a specific style for your button, and use that.

In pre-v11, this will create an old-style spinner, but that's actually good - a v11 spinner would look out of place in pre-v11 environment.