自定義View(一)可拖拽的懸浮控制元件
可拖拽的懸浮控制元件是個比較常見的很簡單的效果,主要知識點:
1.View的簡單自定義,onDraw的重寫等
2.View事件的簡單應用
我們在這個可拖拽的View上加個黃色的線,簡單操作下這個View的樣子,另外,給這個拖拽View加上偏左吸左偏右吸右的效果。下面直接上程式碼:
public class CustomView extends android.support.v7.widget.AppCompatTextView { private Paint paint;//畫筆 private int lastX;//記錄上一個X座標 private int lastY;//記錄上一個Y座標 public CustomView(Context context) { super(context); initDraw(); } public CustomView(Context context, @NullableAttributeSet 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(); //設定上下左右的座標臨界值 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; //設定上下左右的座標為臨界值時相關變數的值 if(top==0){ bottom =getHeight(); } if(left==0){ right=getWidth(); } if(right==pWidth){ left=pWidth-getWidth(); } if(bottom==pHeight){ top=pHeight-getHeight(); } //判斷時間種類 switch (event.getAction()) { case MotionEvent.ACTION_DOWN: lastX = x; lastY = y; break; case MotionEvent.ACTION_MOVE: layout(left, top, right, bottom);//移動式更新佈局 break; case MotionEvent.ACTION_UP: //鬆開手時根據元件中間的位置,判斷吸左吸右 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,把這個元件直接在佈局中展示就行了,很簡單。
demo git地址