我制作了一个具有该OnTouchEvent(MotionEvent event)
方法的自定义视图。这会使视图在按下时改变颜色。
我还OnTouchListener
为我的活动实现了一个,然后通过这样做向它注册视图。view.setOnTouchListener(this);
这带来了一个问题,这意味着只有活动的OnTouchListener
工作。
有针对这个的解决方法吗?
这是我尝试评论中给出的链接后的代码。对不起金额!:
我的自定义视图:
public class DotView extends View implements OnTouchListener {
int RADIUS = 30;
int prevRADIUS;
private Paint paint = new Paint();
float mTranslateX;
float mTranslateY;
int dotX, dotY, color;
private Activity context = null;
public void ReservedCanvas(Activity context) {
super(context);
this.context = context;
this.paint = new Paint();
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
paint.setAntiAlias(true);
}
public DotView(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(6f);
paint.setStyle(Paint.Style.FILL);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setColor(Color.BLACK);
}
public void setColor(int color) {
paint.setColor(color);
invalidate();
}
public int getColor() {
return paint.getColor();
}
public void setRadius(int radius) {
RADIUS = radius;
invalidate();
}
public int getRadius() {
return RADIUS;
}
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.translate(mTranslateX, mTranslateY);
canvas.drawCircle(0, 0, RADIUS, paint);
canvas.restore();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int dia = RADIUS * 4;
int w = resolveSize(dia, widthMeasureSpec);
int h = resolveSize(dia, heightMeasureSpec);
setMeasuredDimension(w, h);
float radius = Math.min(w, h) / 2F;
mTranslateX = radius;
mTranslateY = radius;
}
private void setOnTouchFeedback(Boolean bool) {
// TODO Check this works
if (bool == true) {
int rad = getRadius();
prevRADIUS = rad;
float touchedRad = (float) (rad * 1.4);
int rounded = Math.round(touchedRad);
setRadius(rounded);
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction() & MotionEvent.ACTION_MASK;
switch (action) {
case MotionEvent.ACTION_DOWN: {
this.pointerPressed(event);
break;
}
case MotionEvent.ACTION_MOVE: {
this.pointerDragged(event);
break;
}
case MotionEvent.ACTION_UP: {
this.pointerReleased();
break;
}
}
return true;
}
protected void pointerPressed(MotionEvent event) {
// you can save touch point here!
setOnTouchFeedback(true);
}
protected void pointerDragged(MotionEvent event) {
// for get x ==> eveevent.getX()
// for get y ==> eveevent.getY()
this.repaint();
}
protected void pointerReleased() {
}
public void repaint() {
this.invalidate();
}
}