我自己写了extends View
,但效果不好。它的目的是允许拖动红色圆圈。不幸的是,圆在拖动过程中会振动,即移动不顺畅:
public class FieldView extends View {
private int cellWidth;
private int cellHeight;
private float startleft, starttop;
private float startx, starty;
private Paint paint;
public FieldView(Context context) {
super(context);
paint = new Paint();
paint.setColor(Color.RED);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawOval(new RectF(
getTranslationX()-(float)cellWidth/2f,
getTranslationY() - (float)cellHeight/2f,
getTranslationX() + (float)cellWidth/2f,
getTranslationY() + (float)cellHeight/2f), paint);
}
public void setCellWidth(int value) {
this.cellWidth = value;
}
public void setCellHeight(int value) {
this.cellHeight = value;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if( event.getActionMasked() == MotionEvent.ACTION_DOWN ) {
startx = event.getX();
starty = event.getY();
startleft = getTranslationX();
starttop = getTranslationY();
return true;
}
else if( event.getActionMasked() == MotionEvent.ACTION_UP ) {
setTranslationX( startleft + (event.getX() - startx) );
setTranslationY( starttop + (event.getY() - starty) );
invalidate();
startx = starty = 0;
return true;
}
else if( event.getActionMasked() == MotionEvent.ACTION_MOVE ) {
setTranslationX( startleft + (event.getX() - startx) );
setTranslationY( starttop + (event.getY() - starty) );
invalidate();
return true;
}
else {
return false;
}
}
}
亚军:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FieldView fieldView = new FieldView(this);
fieldView.setCellHeight(100);
fieldView.setCellWidth(100);
setContentView(fieldView);
}
问题是:为什么?
编辑 1
我认为这不是噪音,因为跳跃的幅度相对较大。
固定的
这是一个错误。我对 get/setTranslationX/Y() 的使用干扰了触摸事件坐标。显然,事件考虑了翻译。当我切换到自己的翻译领域时,振动消失了。