user1643156 user1643156 - 1 month ago 7
Android Question

Removing deafult background of ImageButton in Android but keep onClick highlight

I have a few ImageButtons in my app and I'v removed the default grey background with

android:background="@android:color/transparent"
or
android:background="@null"


The problem is, it also removes the onClick highlight background (orange in API8 and blue in API16)

I'v read so many Q&A here, people are all suggesting to use
selector
.Instead of making another image for each of the buttons, I'd like to have a background color highlight only. Is there a simple way to achieve this?

solution: programmatically

import android.view.View;
import android.view.View.OnTouchListener;

// ...

btn.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == (MotionEvent.ACTION_DOWN)) {
// set background highlight color
btn.setBackgroundResource(R.color.blue);
}
if(event.getAction() == (MotionEvent.ACTION_UP)) {
// restore transparent
btn.setBackgroundResource(
getResources().getColor(android.R.color.transparent));
}
return false;
}
});


It isn't that simple, but does the job and saves me a lot of time making another image for each button while I don't really need fancy onclick styles.

Answer

You really need to use a selector for this.

You can use colors for your backgrounds in your selectors, it doesn't need to be a PNG resource (just set the background to a color, instead of a drawable resource).

You will place this code in your drawable folder, with a specific name (like button_sel.xml).

Then you set this as the background to your button in your XML it would look like this:

android:background="@drawable/button_sel"

The selector would look something like this:

<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@color/ab_background"
        android:state_focused="true"
        android:state_pressed="true"/>
    <item
        android:drawable="@color/ab_background"
        android:state_focused="false"
        android:state_pressed="true"/>
    <item
        android:drawable="@color/ab_background_on"
        android:state_focused="true"
        android:state_pressed="false"/>
    <item
        android:drawable="@color/ab_background_on"
        android:state_focused="false"
        android:state_pressed="false"/>
</selector>