要實現最簡單的懸浮小球需要解決兩個小問題:
1:需要判斷是否起始的觸摸屏幕在該懸浮球上面
2:自由拖動View
先解決第一個問題:
public class Point extends View {
private Paint mPaint;
//判斷是否再裏面
private boolean isIn = false;
private int lastX;
private int lastY;
public Point(Context context) {
super(context, null);
}
public Point(Context context, @Nullable AttributeSet attrs) {
super(context, attrs, 0);
}
public Point(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint = new Paint();
mPaint.setColor(Color.parseColor("#121212"));
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(Color.parseColor("#91bef0"));
canvas.drawCircle(0.5f * getWidth(), 0.5f * getWidth(), 0.5f * getWidth(), mPaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int[] location = new int[2];
this.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
if (event.getX() < x || event.getX() > (x + this.getWidth()) || event.getY() < y || event.getY() > (y + this.getHeight())) {
return true;
} else {
return super.onTouchEvent(event);
}
}
}
主要看onTouchEvent裏面的這一段:
int[] location = new int[2];
this.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
if (event.getX() < x || event.getX() > (x + this.getWidth()) || event.getY() < y || event.getY() > (y + this.getHeight())) {
return true;
} else {
return super.onTouchEvent(event);
}
return true 上面就是點擊到該View的處理
else裏面就是默認方法。
接下來解決第二步:自由拖拽
相關的代碼就是寫在上面的true裏面
@Override
public boolean onTouchEvent(MotionEvent event) {
int[] location = new int[2];
this.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
if (event.getX() < x || event.getX() > (x + this.getWidth()) || event.getY() < y || event.getY() > (y + this.getHeight())) {
//移動
int xx = (int) event.getX();
int yy = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = xx;
lastY = yy;
break;
case MotionEvent.ACTION_MOVE:
int offX = xx - lastX;
int offY = yy - lastY;
offsetLeftAndRight(offX);
offsetTopAndBottom(offY);
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
} else {
return super.onTouchEvent(event);
}
}
這個是整個onTouchEvent的方法
然後在佈局文件裏面初始化就可以了。
但是,現在要在Java代碼裏面添加的話:
public class MainActivity extends AppCompatActivity {
private RelativeLayout mRe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRe = (RelativeLayout) findViewById(R.id.re);
mRe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LogUtil.fussenLog().d("外面 父控件");
}
});
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(250, 250);
params.topMargin = 250;
params.leftMargin = 250;
Point p = new Point(this);
mRe.addView(p,params);
}
}
裏面的250 代表的起始是像素點。。。
------------------------------------------------------------------------------------------------------------
OK完成