在我的 Android 应用程序中,我有一个 GridView,它显示一组图像,每个图像都位于 ImageView (TickedImageView) 的自定义子类中,当图像被选中时会显示一个刻度。我想要实现的是在触摸图像时显示波纹。我尝试将背景设置为
?android:attr/selectableItemBackground
没有运气,还添加了具有此背景的包装器布局,但似乎没有任何效果。
我的代码如下:
<GridView
android:id="@+id/photos_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:horizontalSpacing="2dp"
android:numColumns="@integer/photos_grid_num_columns"
android:stretchMode="columnWidth"
android:verticalSpacing="2dp"
android:layout_below="@id/spinner_toolbar" />
每个 GridView 项的布局如下:
<utils.TickedImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/thumb"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?android:attr/selectableItemBackground"
android:focusable="true"
android:clickable="true" />
ImageView 子类(TickedImageView)如下:
package utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import app.R;
public class TickedImageView extends ImageView {
private boolean selected;
private Bitmap mTickBmp;
private Paint mDarkerPaint;
private View.OnClickListener onImageClickListener;
private int x, y;
public TickedImageView(Context context) {
super(context);
init();
}
public TickedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
super.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setSelected(!isSelected());
if (onImageClickListener != null)
onImageClickListener.onClick(TickedImageView.this);
}
});
mDarkerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mDarkerPaint.setStyle(Paint.Style.FILL);
mDarkerPaint.setColor(0x80142030);
mTickBmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_done_white_48px);
}
public void setSelected(boolean selected) {
this.selected = selected;
invalidate();
}
public boolean isSelected() {
return selected;
}
@Override
protected void onDraw(@NonNull Canvas canvas) {
super.onDraw(canvas);
if (selected) {
canvas.drawRect(0, 0, canvas.getWidth(), getMeasuredWidth(), mDarkerPaint);
canvas.drawBitmap(mTickBmp, x, y, null);
}
}
@Override
public void setOnClickListener(OnClickListener listener) {
onImageClickListener = listener;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
x = (getMeasuredWidth() / 2) - (mTickBmp.getWidth() / 2);
y = (getMeasuredWidth() / 2) - (mTickBmp.getHeight() / 2);
}
}
谢谢你。