Android滑动(二)——滑动方法之layout() 及相应封装API

Android视图拖拽实现

前边我们学了Android坐标系和触控事件,滑动效果原理:通过滑动时的偏移量,来修改View的坐标。

一、layout方法

(1)自定义View的代码:

package com.datong.dragview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by lyj on 2016/4/14.
 */
public class DragView extends View {
    private int lastX;
    private int lastY;
    public DragView(Context context) {
        super(context);
    }

    public DragView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public DragView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @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;
                int offSetY = y- lastY;
                //当前left、top、right、buttom的基础上加上偏移量
                layout(getLeft() + offSetX,
                        getTop() + offSetY,
                        getRight() + offSetX,
                        getBottom() + offSetY
                        );
                break;
            case MotionEvent.ACTION_UP:
                break;
        }


        return true;
    }
}
(2)、布局的代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.datong.dragview.DragView
        android:layout_centerInParent="true"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="#FF0000"
        />
</RelativeLayout>


二、offsetLeftAndRight()和offsetTopAndBottom()
系统对上下左右移动的API的封装

offsetLeftAndRight(offSetX);
//同时对top和Bottom进行偏移
offsetTopAndBottom(offSetY);


三、LayoutParams

ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) getLayoutParams();
layoutParams.leftMargin = getLeft() + offSetX;
layoutParams.rightMargin = getTop() + offSetY;
setLayoutParams(layoutParams);




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值