For a custom AdapterView implementation I'd like to add a color overlay to selected items. How do I add a color overlay to a child of my AdapterView?
Asked
Active
Viewed 9,257 times
6
-
http://stackoverflow.com/questions/14023886/android-button-selector/14024007#14024007 – Chintan Rathod Nov 13 '13 at 12:39
-
I don't want to change the background of the child elements. I would like to add a color overlay. Also this should be a generic solotion as I don't know what type of view the child represents. – multiholle Nov 13 '13 at 12:41
-
Then put a `CustomView` or `ImageView` over your item of list view. When selected, just change color of `CustomView` or `ImageView`. – Chintan Rathod Nov 13 '13 at 12:44
2 Answers
10
If you are using your own layout simply change the container to RelativeLayout
(or a Layout class that inherits from RelativeLayout
), and put the color overlay after the main layout. All you need is to add a View
and set it's background and alpha. alpha
set to the value 1 will activate this overlay, whereas setting alpha
to 0 will go back to normal.
Example:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- add your views here -->
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#8000FF00" />
</RelativeLayout>
This will overlay a green layer with 50% alpha over the other views which are before it in the layout.
5
OK, I did some more research. That's what I finally came up with:
// prepare a gray filter setting saturation to 0, or ...
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
Paint paint = new Paint();
ColorFilter filter = new ColorMatrixColorFilter(cm);
// ... prepare a color filter
ColorFilter filter = new PorterDuffColorFilter(Color.rgb(34, 136, 201), PorterDuff.Mode.OVERLAY);
// create paint
paint.setColorFilter(filter);
// override dispatchDraw of the view
@Override
protected void dispatchDraw(Canvas canvas) {
if (isPressed()) {
canvas.saveLayer(null, paint, Canvas.ALL_SAVE_FLAG);
super.dispatchDraw(canvas);
canvas.restore();
} else {
super.dispatchDraw(canvas);
}
}

multiholle
- 3,050
- 8
- 41
- 60