Andorid开发自定义View(二)

View滑动

当点击事件传达到View时,系统记下触摸点的坐标,手指移动时系统记下后触摸的坐标并算出偏移量,并通过偏移量来修改View的坐标。

1 layout()方法

 

public class CustomView extends View
{
    public CustomView(Context context)
    {
        super(context);
    }

    public CustomView(Context context, @Nullable AttributeSet attrs)
    {
        super(context, attrs);
    }

    public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
    }

    private int lastX;
    private int lastY;

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        int x = (int) event.getX();//得到距离父控件左边距
        int y = (int) event.getY(); //得到距离父控件顶边距
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                lastX = x;
                lastY = y;
                break;
            case MotionEvent.ACTION_MOVE:
                //计算移动的距离
                int offsetX = x - lastX;//移动的X轴距离
                int offsetY = y - lastY;//移动的Y轴距离
                //调用layout方法来重新放置它的位置
                layout(getLeft() + offsetX,//当前距离父边距的左边的距离  +   移动的X轴距离
                        getTop() + offsetY,
                        getRight() + offsetX,
                        getBottom() + offsetY);
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        return true;
    }

}

2 offsetLeftAndRight(offsetX);和offsetTopAndBottom(offsetY);

在MotionEvent.ACTION_MOVE中可以使用下面写法

该方法可以替换掉layout()方法

3 LayoutParams(改变布局参数)

LinearLayout.LayoutParams用于保存View的布局参数,因此我们可以通过LinearLayout.LayoutParams来改变View的布局参数从而达到改变View位置的效果。

在MotionEvent.ACTION_MOVE中可以使用下面写法

写法一

 LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) getLayoutParams();//父控件是什么就用什么布局下的LayoutParams
                layoutParams.leftMargin = getLeft() + offsetX;
                layoutParams.topMargin = getTop() + offsetY;
                setLayoutParams(layoutParams);

写法二

ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) getLayoutParams();//父控件是什么就用什么布局下的LayoutParams
                marginLayoutParams.leftMargin = getLeft() + offsetX;
                marginLayoutParams.topMargin = getTop() + offsetY;
                setLayoutParams(marginLayoutParams);

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值