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.
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:
The selector would look something like this: