android之滑屏的实现
★理论知识
●View在屏幕上显示出来要先经过measure(计算)和layout(布局)。
◆当控件的父元素正要放置该控件时调用,父元素会问子控件“你想要用多大的地方?”,然后传入两个参数widthMeasureSpec和heightMeasureSpec,这两个参数指明控件可获得的空间以及关于这个空间描述的元数据。
◆更好的方法是你传递View的高度和宽度到setMeasureDimension方法里,这样可以直接告诉父控件需要多大地方放置子控件。
◆示例:
@Override
protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec){int measuredHeight=measureHeight(heightMeasureSpec);int measuredWidth=measureWidth(widthMeasureSpec);setMeasuredDimension(measureHeight,measuredWidth);}private int measureHeight(int measureSpec){//Return measured widget height.int specMode=MeasureSpec.getMode(measureSpec);
int specSize=MeasureSpec.getSize(measureSpec);
int result=0;
if(specMode == MeasureSpec.AT_MOST){
result=specSize;
}else if(specMode==MeasureSpec.EXACTLY){
result=specSize;
}
return result;
}private int measureWidth(int measureSpec){//Return measured widget width.int specMode=MeasureSpec.getMode(measureSpec);
int specSize=MeasureSpec.getSize(measureSpec);
int result=0;
if(specMode == MeasureSpec.AT_MOST){
result=specSize;
}else if(specMode==MeasureSpec.EXACTLY){
result=specSize;
}
return result;
}
边界参数widthMeasureSpec和heightMeasureSpec效率原因以整数的方式传入。在使用之前首先要做的是使用MeasureSpec类的静态方法getMode和getSize来译解。
int specMode=MeasureSpec.getMode(measureSpec);
int specSize=MeasureSpec.getSize(measureSpec);
根据specMode的值(MeasureSpec有3种模式分别是UNSPECIFIED、EXACTLY、AT_MOST)
如果是AT_MOST,specSize代表的是最大可获得的空间
如果是EXACTLY,specSize代表的是精确的尺寸
如果是UNSPECIFIED,对于控件尺寸来说,没有任何参考意义
◆这些模式和设置的layout参数的fill_parent、wrap_content是什么关系呢?
当设置width或height为fill_parent时,容器在布局时调用子view的measure方法,传入的模式是EXACTLY,因为子view会占据剩余容器的空间,所以它大小是确定的。当设置为wrap_content时,容器传进去的是AT_MOST,表示子view的大小最多是多少,这样子view会根据上限来设置自己的尺寸。当子view的大小设置为精确值时,容器传入的是EXACTLY。
●VelocityTracker用来追踪触摸事件(flinging事件和其他手势事件)的速率。
◆用obtain()函数来获得类的实例,用addMovement(MotionEvent)函数将motion event加入到VelocityTracker类实例中,当你使用到速率时,使用computeCurrentVelocity(int)初始化速率的单位,并获得当前的事件的速率,然后使用getXVelocity()或getYVelocity()获得横向和竖向的速率。
◆VelocityTracker.computeCurrentVelocity(int units,float maxVelocity)用来计算已经发生触摸事件点的当前速率。这个函数只有在你需要得到速率消息的情况下才调用,因为使用它需要消耗很大的性能。参数units为速率单位,值为1的意思是以一毫秒运动了多少个像素的速率,1000表示一秒时间内运动了多少个像素。maxVelocity代表这个方法能计算出事件的最大速率,值和units的值具有一样的单位。
◆示例:
private VelocityTracker velocityTracker;
//在onTouchEvent(MotionEvent ev)中
if(velocityTracker==null){
velocityTracker=VelocityTracker.obtain();//获得VelocityTracker类实例
}
velocityTracker.addMovement(ev);//将事件加入到VelocityTracker类实例中
★实现代码:
import java.util.ArrayList;import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
public class TouchPageTransfer extends ViewGroup {
/**
* 手势临界速度,当速度超过这个时切换到下一屏
*/
private final static int SNAP_VELOCITY = 100;
/**
* 停止状态
*/
private final static int TOUCH_STATE_REST = 0;
/**
* 滚动状态
*/
private final static int TOUCH_STATE_MOVING = 1;
/**
* 减速停止状态
*/
private final static int TOUCH_STATE_SLOWING = 2;
/**
* 移动的阈值
*/
private static final int TOUCH_SLOP = 10;
private Context context;
/**
* 速度跟踪
*/
private VelocityTracker velocityTracker;
/**
* 速度最大值
*/
private int maximumVelocity;
/**
* 当前触摸状态
*/
private int touchState = TOUCH_STATE_REST;
/**
* 触摸起始点坐标
*/
private float lastMotionX;
private float lastMotionY;
/**
* 是否移动了
*/
private boolean isMoved;
private List<LinearLayout> views;
private LinearLayout view1;
private LinearLayout view2;
private LinearLayout view3;
public TouchPageTransfer(Context context) {
super(context);
// TODO Auto-generated constructor stub
this.context = context;
init();
}
private void init() {
views = new ArrayList<LinearLayout>();
view1 = new LinearLayout(context);
view1.setBackgroundColor(Color.YELLOW);
this.addView(view1);
TextView tv = new TextView(context);
tv.setText("测试");
view1.addView(tv);
views.add(view1);
view2 = new LinearLayout(context);
view2.setBackgroundColor(Color.RED);
this.addView(view2);
views.add(view2);
view3 = new LinearLayout(context);
view3.setBackgroundColor(Color.GREEN);
this.addView(view3);
views.add(view3);
final ViewConfiguration configuration = ViewConfiguration
.get(getContext());
maximumVelocity = configuration.getScaledMaximumFlingVelocity();
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// TODO Auto-generated method stub
int viewLeft = -1;
int count = views.size();
//水平从左到右放置View
for (int i = 0; i < count; i++) {
View view = views.get(i);
if (view.getVisibility() != View.GONE) {//View处于显示状态
int viewWidth = view.getMeasuredWidth();
if (viewLeft == -1) {
viewLeft = -viewWidth;
}
view.layout(viewLeft, 0, viewLeft + viewWidth,
view.getMeasuredHeight());
viewLeft += viewWidth;
}
}
}
@Override
protected void onDraw(Canvas canvas) {
//水平从左到右放置
int count = views.size();
for (int i = 0; i < count; i++) {
View view = views.get(i);
drawChild(canvas, view, getDrawingTime());
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int count = views.size();
for (int i = 0; i < count; i++) {
View view = views.get(i);
view.measure(widthMeasureSpec, heightMeasureSpec);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (velocityTracker == null) {
velocityTracker = VelocityTracker.obtain();
}
velocityTracker.addMovement(event);
int action = event.getAction();
float x = event.getX();
float y = event.getY();
switch (action) {
case MotionEvent.ACTION_DOWN:
if (touchState == TOUCH_STATE_REST) {
//记录按下去的坐标
lastMotionX = x;
lastMotionY = y;
//改变触摸状态
touchState = TOUCH_STATE_MOVING;
isMoved = false;
}
break;
case MotionEvent.ACTION_MOVE:
if (touchState == TOUCH_STATE_MOVING) {
//计算位移量,向左为负,向右为正
float offsetX = x - lastMotionX;
float offsetY = y - lastMotionY;
if (isMoved) {
lastMotionX = x;
lastMotionY = y;
int count = views.size();
for (int i = 0; i < count; i++) {
View view = views.get(i);
if (view.getVisibility() != View.GONE) {//对于显示的View才进行布局
int viewWidth = view.getMeasuredWidth();
int viewLeft = view.getLeft() + (int) offsetX;
view.layout(viewLeft, 0, viewLeft + viewWidth,
view.getMeasuredHeight());
viewLeft += viewWidth;
}
}
} else if (Math.abs(offsetX) > TOUCH_SLOP
|| Math.abs(offsetY) > TOUCH_SLOP) {//移动超过阈值,则表示移动了
isMoved = true;
}
}
break;
case MotionEvent.ACTION_UP:
if (isMoved) {
if (touchState == TOUCH_STATE_MOVING) {
touchState = TOUCH_STATE_SLOWING;
int sign = 0;//标志有足够能力移动的移动方向,向左为1,向右为-1,否则为0
//计算当前速度
velocityTracker.computeCurrentVelocity(1000,
maximumVelocity);
//x方向速度
int velocityX = (int) velocityTracker.getXVelocity();
if (velocityX > SNAP_VELOCITY) {//足够的能力向左
sign = 1;
} else if (velocityX < -SNAP_VELOCITY) {//足够的能力向右
sign = -1;
} else {
sign = 0;
}
moveToFitView(sign);
if (velocityTracker != null) {
velocityTracker.recycle();//回收VelocityTracker对象
velocityTracker = null;
}
}
}
break;
default:
break;
}
return true;
}
/**
* 总的位移量,向右为正,向左为负
*/
int tOffsetX = 0;
private void moveToFitView(int sign) {
swapView(sign);
int left = views.get(1).getLeft();
tOffsetX = 0;
if (left != 0) {
tOffsetX = -left;
}
moveView();
}
FlipAnimationHandler flipAnimationHandler;
int ovv = 40;//每次预期moveView位移量
/**
* 移动View
*/
private void moveView() {
int count = views.size();
if (tOffsetX != 0) {
int ov = 0;//本次moveView位移量,向右为正,向左为负
if (tOffsetX > 0) {//向右
ov = ovv;
} else {//向左
ov = -1 * ovv;
}
ovv -= 3;
if (ovv < 1) {
ovv = 3;
}
if (Math.abs(tOffsetX) < Math.abs(ov)) {//总位移量的绝对值小于本次位移量的绝对值
ov = tOffsetX;
tOffsetX = 0;
} else {
tOffsetX -= ov;
}
//水平从左到右放置
for (int i = 0; i < count; i++) {
View view = views.get(i);
int viewWidth = view.getMeasuredWidth();
int viewLeft = view.getLeft() + ov;
view.layout(viewLeft, 0, viewLeft + viewWidth,
view.getMeasuredHeight());
viewLeft += viewWidth;
}
if (flipAnimationHandler == null) {
flipAnimationHandler = new FlipAnimationHandler();
}
flipAnimationHandler.sleep(1);
} else {
ovv = 40;
touchState = TOUCH_STATE_REST;
}
}
class FlipAnimationHandler extends Handler {
@Override
public void handleMessage(Message msg) {
TouchPageTransfer.this.moveView();//
}
public void sleep(long millis) {
this.removeMessages(0);
sendMessageDelayed(obtainMessage(0), millis);
}
}
/**
* 向左移动时将原来最左边的View移到最右边,向右移动时将原来最右边的View移到最左边,并根据当前其他的View布局移动的这个View
* @param sign 1代表向左移动,-1代表向右移动,0代表不移动
* @return
*/
private boolean swapView(int sign) {
boolean flag = false;
if (sign == -1) {//向左
View view0 = views.get(0);
if (view0.getLeft() <= -1 * view0.getMeasuredWidth()) {
swapViewIndex(sign);
View view1 = views.get(1);
View view2 = views.get(2);
int viewLeft = view1.getLeft() + view1.getMeasuredWidth();
view2.layout(viewLeft, 0, viewLeft + view2.getMeasuredWidth(),
view2.getMeasuredHeight());
flag = true;
}
} else if (sign == 1) {//向右
View view2 = views.get(2);
if (view2.getLeft() >= view2.getMeasuredWidth()) {
swapViewIndex(sign);
View view0 = views.get(0);
View view1 = views.get(1);
int viewLeft = view1.getLeft() - view0.getMeasuredWidth();
view0.layout(viewLeft, 0, viewLeft + view0.getMeasuredWidth(),
view0.getMeasuredHeight());
flag = true;
}
}
return flag;
}
/**
* 向左移动时将原来最左边的View移到最右边,向右移动时将原来最右边的View移到最左边
* @param sign 1代表向左移动,-1代表向右移动,0代表不移动
*/
private void swapViewIndex(int sign) {
if (sign == -1) {//向左
LinearLayout v = views.remove(0);
views.add(v);
} else if (sign == 1) {//向右
LinearLayout v = views.remove(views.size() - 1);
views.add(0, v);
}
}
}
作者:sy
出处:http://www.cnblogs.com/sydeveloper
QQ:522733724
本页版权归作者和博客园所有,欢迎转载,但未经作者同意必须保留此段声明,
且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利