6

对于自定义 AdapterView 实现,我想为所选项目添加颜色叠加。如何向我的 AdapterView 的子项添加颜色叠加层?

4

2 回答 2

10

如果您使用自己的布局,只需将容器更改为RelativeLayout(或继承自的 Layout 类RelativeLayout),并将颜色叠加层放在主布局之后。您只需要添加一个View并设置它的背景和 alpha。alpha设置为值 1 将激活此覆盖,而设置alpha为 0 将恢复正常。

例子:

<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>

这将在布局中它之前的其他视图上覆盖一个具有 50% alpha 的绿色层。

于 2013-11-13T12:40:51.280 回答
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);
    }
}
于 2013-11-14T06:49:33.423 回答