(Now I have come across related questions on StackOverflow but unfortunately none of the solutions worked for me which is why I had to ask this separately)
I am a Novice to Android. The problem: I need to have an image that acts as a button. Now I understand that this can be achieved by either using an image on a standard button or by using something called as "ImageButton" (which I guess is highly recommended although I have no idea why).
Requirements: I need detailed guidance for going about this problem. Specifically, I thought the "putting-image-on-standard-button" was easier until I faced two major issues: I was unable to set the image in the center (thanks drawable-top,bottom,left6,right) and once I changed the background color to match that of the Activity screen's back-color, the button effect disappeared. Simply put, I need a moderately easy way of having an image act as a button or a button with an image which has all three effects: focussed, pressed and default. I used ImageButton but then I did not know how to make custom shapes or 9patch images to give it all the desired effects, I am pretty satisfied with the default button that android provided. All I simply need is something like a background hover over the image or something of that sort which indicates the user that the image is being pressed and the event has been generated!
Can someone please help me out with this? I need the UI to look decent and therefore, need the corresponding effects on my image/button. Thanks in Advance :)
This is my icon-image:
I wish to have some sort of hover effect around this that indicates that the image has been pressed just like any normal button.
Use ImageButton
and StateList Drawable. You need selector for different button's states. You can assign different drawable for different state to imitate the onFocus or onPressed effect on normal button.
This is selector.xml
in drawable
folder under res
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@color/cyan"/> <!-- pressed state -->
<item android:state_focused="true"
android:drawable="@color/cyan"/> <!-- focused state -->
<item android:drawable="@android:color/transparent"/> <!-- default state -->
</selector>
And this is color.xml
in values
folder under res
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="cyan">#33B5E5</color>
</resources>
Set the ImageButton
's src to your image and set the background to selector.xml
.
This is the final result:
There is a good tutorial here: Android ImageButton Selector Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With