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

来源:互联网 发布:梅甘娜rs 知乎 编辑:程序博客网 时间:2024/06/01 10:05

前边我们学了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);




0 0
原创粉丝点击