user1012480 user1012480 - 8 days ago 5
Android Question

Star Button in Android

I'd like to put one star-shaped button in my app, just like a rating star. I've already tried to use a one star rating bar, but unfortunately it doesn't work as a button.

I'd like it to work as a button, even better if the background of the selected state is yellow...any suggestions? Thanks.

Answer

Sure, use a layout resource like this:

<ImageButton android:id="@+id/favorite"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:src="@drawable/star"
        android:background="#00ffffff"
        android:onClick="onToggleStar"/>

You can pair this with a state list drawable defined like this that is saved as an XML file at res/drawable/star.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:drawable="@drawable/button_pressed" /> <!-- pressed -->
    <item android:state_focused="true"
          android:drawable="@drawable/button_focused" /> <!-- focused -->
    <item android:state_hovered="true"
          android:drawable="@drawable/button_focused" /> <!-- hovered -->
    <item android:drawable="@drawable/button_normal" /> <!-- default -->
</selector>

Here are the images that pack with Android itself:

  • Off Off
  • On On
  • Disabled Disabled
  • On Pressed On Pressed
  • Off Pressed Off Pressed
Comments