可拖拽的懸浮控件是個(gè)比較常見(jiàn)的很簡(jiǎn)單的效果眯亦,主要知識(shí)點(diǎn):
1.View的簡(jiǎn)單自定義化戳,onDraw的重寫等
2.View事件的簡(jiǎn)單應(yīng)用
我們?cè)谶@個(gè)可拖拽的View上加個(gè)黃色的線搜吧,簡(jiǎn)單操作下這個(gè)View的樣子偎蘸,另外帚称,給這個(gè)拖拽View加上偏左吸左偏右吸右的效果嘹叫。下面直接上代碼:
public class CustomView extends android.support.v7.widget.AppCompatTextView {
private Paint paint;//畫筆
private int lastX;//記錄上一個(gè)X坐標(biāo)
private int lastY;//記錄上一個(gè)Y坐標(biāo)
public CustomView(Context context) {
super(context);
initDraw();
}
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
initDraw();
}
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initDraw();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
int rawX = (int) event.getRawX();
int rawY = (int) event.getRawY();
int offsetX = x - lastX;
int offsetY = y - lastY;
ViewGroup mViewGroup = (ViewGroup) getParent();
//取組件父集的寬高
int pWidth = mViewGroup.getWidth();
int pHeight = mViewGroup.getHeight();
//設(shè)置上下左右的坐標(biāo)臨界值
int left = getLeft() + offsetX;
left = left <= 0 ? 0 : left;
int top = getTop() + offsetY;
top = top <= 0 ? 0 : top;
int right = getRight() + offsetX;
right = right >= pWidth ? pWidth : right;
int bottom = getBottom() + offsetY;
bottom = bottom >= pHeight ? pHeight : bottom;
//設(shè)置上下左右的坐標(biāo)為臨界值時(shí)相關(guān)變量的值
if(top==0){
bottom =getHeight();
}
if(left==0){
right=getWidth();
}
if(right==pWidth){
left=pWidth-getWidth();
}
if(bottom==pHeight){
top=pHeight-getHeight();
}
//判斷時(shí)間種類
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = x;
lastY = y;
break;
case MotionEvent.ACTION_MOVE:
layout(left, top, right, bottom);//移動(dòng)式更新布局
break;
case MotionEvent.ACTION_UP:
//松開(kāi)手時(shí)根據(jù)組件中間的位置,判斷吸左吸右
if (rawX <= pWidth / 2) {
layout(0, top, getWidth(), bottom);
} else {
layout(pWidth - getWidth(), top, pWidth, bottom);
}
break;
}
return true;
}
/**
* 初始化畫筆
* */
private void initDraw() {
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.YELLOW);
paint.setStrokeWidth(1.5f);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
//畫布劃線
canvas.drawLine(0, height / 2, width, height / 2, paint);
}
}
ok丛肢,把這個(gè)組件直接在布局中展示就行了围肥,很簡(jiǎn)單。
demo git地址