カスタム imageview を実装したいのですが、背景を自動的に灰色に変えることができますが、問題はビューが onclick イベントに応答できないことです。効果が無効です。どうすればよいかわかりません。
package com.test;
import android.content.Context;
import android.graphics.ColorMatrixColorFilter;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;
/**
* the class for the ImageView to automatic turn background to gray
*
* @author jinningwei
*
*/
public class AutoGrayImageView extends ImageView {
public AutoGrayImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
private boolean canAutoGray = true;
/**
* set the function of autogray whether enabled
*
* @param enabled
*/
public void enableAutoGray(boolean enabled) {
canAutoGray = enabled;
}
private float grayscale = 0.2f;
/**
* set gray degree
*
* @param grayscale
*/
public void setGrayscale(float grayscale) {
if (grayscale > 0.5f) {
grayscale = 0.5f;
return;
}
if (grayscale < 0.0f) {
grayscale = 0.0f;
return;
}
this.grayscale = grayscale;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (canAutoGray) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
float[] gray_matrix = { grayscale, grayscale, grayscale, 0.0f, 0.0f, // red
grayscale, grayscale, grayscale, 0.0f, 0.0f, // green
grayscale, grayscale, grayscale, 0.0f, 0.0f, // blue
0.0f, 0.0f, 0.0f, 1.0f, 0.0f, // alpha
};
this.getBackground().setColorFilter(new ColorMatrixColorFilter(gray_matrix));
invalidate();
return true;
case MotionEvent.ACTION_UP:
float[] reset_matrix = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // red
0.0f, 1.0f, 0.0f, 0.0f, 0.0f,// green
0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // blue
0.0f, 0.0f, 0.0f, 1.0f, 0.0f, // alpha
};
this.getBackground().setColorFilter(new ColorMatrixColorFilter(reset_matrix));
invalidate();
return false;
}
}
return super.onTouchEvent(event);
}
}