您的位置:首页 > 移动开发 > Android开发

Android 实现滑动的几种方法(二)LayoutParams

2015-11-22 16:52 671 查看
通过改变layoutParams 来改变一个View的位置时,通常改变的是这个View的Margin属性

package com.example.administrator.myapplication;

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

/**
* Created by Administrator on 2015/11/22 0022.
*/
public class MyView extends View {
int lastX ;
int lastY ;
public MyView(Context context) {
super(context);
}

public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@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 offx = x - lastX;
int offy = y - lastY;
/*
*   通过改变layoutParams 来改变一个View的位置时,通常改变的是这个View的Margin属性
*
*/
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) getLayoutParams();
params.leftMargin = getLeft()+offx;
params.topMargin = getTop()+offy;
setLayoutParams(params);
lastX = x;
lastY = y;

break;
}
return true;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  im android