Issue
I'm trying to achieve buttons similar to the icons in the Action Bar, i.e. transparent images that change background colour on click.
These are the conditions I'd like to satisfy:
- Background colour changes on click
- Contains a small rectangle shape in the center
- Rectangle can change colour programmatically
I tried using a Drawable
to represent the rectangle and then to set it as the background of the button, but it expanded to the edges of the button and so there was no background colour to change when clicked (I was able to use drawable.setColorFilter() and button.setBackground(drawable) to alter its colour however). Shrinking the button also shrank the touch-target.
I also tried using a StateListDrawable
containing two rectangle shapes, a background and an inner rectangle, so on state_pressed
the background rectangle would change colour. However the front rectangle stretched again and completely covered he background rectangle.
Which method can achieve my conditions? Thanks.
Solution
This talk from Google IO 2013 on Android UI design by Nick Butcher and Roman Nurik helped to solve the problem.
The XML attribute style="?android:borderlessButtonStyle"
can be set on an ImageButton
(or even just a Button
) to give it a transparent background which lights up in a standard Holo blue colour on touch. According to Roman Nurik, this attribute provides the standard styling "all for free".
I created an ImageButton
containing that borderless button attribute in my layout.xml file, then I created my coloured Drawable
in Java and put it inside the button using myImageButton.setImageDrawable(myColouredDrawable);
to fit all three of my conditions.
Edit July 2013: To bring the ActionBar pattern to older versions of Android using Jake Wharton's ActionBarSherlock, use style="@style/Widget.Sherlock.ActionButton"
, or if using the ActionBarCompat Support Library, use style="@style/Widget.AppCompat.ActionButton"
Update May 2017: For ImageViews (I believe it is actually an ImageViewCompat
) I am using android:background="?android:attr/selectableItemBackground"
on Jellybean onwards.
Answered By - Jaween
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.