在做自定义组件时要记住可以分为三大类:
自制控件:也成为自定义组件
组合控件:就是利用现有的组件,已经存在的组件组合到一起,形成实现一个新的符合需求的组件。
扩展控件:在原有的基础上,增加新的方法,满足需求的控件
自定义继承View的组件,都会执行那些方法
1.在布局文件中引用继承View的组件
<com.example.demod8.DrawView android:layout_width="100dp" android:layout_height="100dp" android:background="#666666" />2.接着系统会在自动调用自定义控件的构造方法,在这里可以初始化各种类对象
public DrawView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); }3.调用OnDraw()方法,在这里可以绘制各种文字,图片类等
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); }4.也可以增加触摸事件(可选)
@Override public boolean onTouchEvent(MotionEvent event) { return true; }
先来看我的效果,就是当按住该图片时滑动,该View会跟随手指滑动的变动位置。
滑动的七中方式
method1(): 使用getX() getY()方法 获取点击坐标 计算偏量后 调用layout(int left, int top ,int right, int bottom) 更改位置。
method2(): 使用getRawX() getRawY()方法 获取绝对位置坐标 计算偏量后 调用layout(int left, int top ,int right, int bottom) 更改位置。
method3(): 使用getRawX() getRawY()方法 获取绝对位置坐标 计算偏量后 offsetLeftAndRight(int offsetX) 实现left right偏移 offsetTopAndBottom(offsetY) 实现top bottom 偏移
method4(): 使用getRawX() getRawY()方法 获取绝对位置坐标 计算偏量后 使用FrameLayout.LayoutParams params params.leftMargin = getLeft()+offsetX; params.topMargin = getTop()+offsetY;
method5(): 使用getRawX() getRawY()方法 获取绝对位置坐标 计算偏量后 ViewGroup.MarginLayoutParams params
params.leftMargin = getLeft()+offsetX;
params.topMargin = getTo