重写View的onTouch方法实现,最后一定要返回true,否则不会起作用
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mDownX = event.getX();
mDownY = event.getY();
break;
case MotionEvent.ACTION_MOVE:
float xOff = event.getX() - mDownX;
float yOff = event.getY() - mDownY;
if (xOff != 0 && yOff != 0) {
int l = (int) (getLeft() + xOff);
int t = (int) (getTop() + yOff);
int r = (int) (getRight() + xOff);
int b = (int) (getBottom() + yOff);
this.layout(l, t, r, b);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
setPressed(false);
break;
}
return true;
}
自定义View的wrap_content宽度, 自定义的View设置wrap_content,需要手动给一个默认尺寸
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int defaultWidth = 100;
int defaultHeight = 100;
int specWidth = MeasureSpec.getSize(widthMeasureSpec);
int specHeight = MeasureSpec.getSize(heightMeasureSpec);
if (getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT &&
getLayoutParams().height == ViewGroup.LayoutParams.WRAP_CONTENT) {
setMeasuredDimension(defaultWidth, defaultHeight);
} else if (getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT) {
setMeasuredDimension(defaultWidth, specHeight);
} else if (getLayoutParams().height == ViewGroup.LayoutParams.WRAP_CONTENT) {
setMeasuredDimension(specWidth, specHeight);
}
}