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

android 控件滑动

2016-02-16 15:45 531 查看
1 对于控件的滑动,可以分为瞬间滑动与弹性滑动.

而 瞬间滑动实现的常用的方式有以下几种:

1 使用 View的scrollTo与scrollBy方法进行滑动.

其代码的本质是改变控件边缘与内容之间距离的mScrollX mScrollY属性来实现滑动,在滑动的过程中,以 控件的边缘为参考系.

其中 scrollTo表示绝对位置的滑动.scrollBy表示相对位置的滑动.

而且,其滑动的是控件中的内容,而非控件本身.

例如:

layout=(LinearLayout) this.findViewById(R.id.linearlayout);

layout.scrollTo(100, 100);

layout.scrollBy(100, 100);


2 使用属性动画实现滑动.

例如:

ObjectAnimator.ofInt(tv, "tanslationX", 0,100).setDuration(100).start();


实现控件的平移动画.

3 通过改变控件的布局参数来实现滑动.

button=(Button) this.findViewById(R.id.button);
MarginLayoutParams lp=(MarginLayoutParams) button.getLayoutParams();
lp.leftMargin+=100;
button.requestLayout();


控件就向右滑动了100像素

控件的弹性滑动可以给用户以良好的体验,实现弹性滑动也存在几种,其基本的策略是 将一次大的滑动在一定时间内分割成若干个小的滑动,从而实现了弹性滑动.

1 Scroller 使用

scroller是实现滑动经常会使用的类,其思路大致是:

scroller调用startScroll ,制定起始的位置,需要滑动的距离,与所需要花费的时间.

其底层会计算随着时间的推移,当前控件应该处在的位置.

所以,我们在适当的位置获取到计算的结果,在调用scrollTo方法即可.

这里,我们所说的适当的位置,一般是指 方法:computeScroll()

该方法是在绘制draw方法中回调的方法.所以,当我们开始滑动的时候,还需要重绘控件.

以下是一段经典代码:

public class ScrollerView extends LinearLayout {

private Scroller mScroller;

@SuppressLint("NewApi")
public ScrollerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

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

public ScrollerView(Context context) {
super(context);

mScroller=new Scroller(context);
}

/**
* 缓慢的滑动
* @param offx
* @param offy
*/
private void smoothScrollTo(int offx,int offy){
int scrollX=getScrollX();
int deltaX=offx-scrollX;
//指定起始的位置 要滑动的距离 与需要花费的时间
mScroller.startScroll(scrollX, 0, deltaX, 0,1000);
//重绘
invalidate();
}

@Override
public void computeScroll() {
// TODO 自动生成的方法存根
//判断滑动是否停止
if(mScroller.computeScrollOffset()){
//获取mScroller当前的位置
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
postInvalidate();
}
}

}


2 使用属性动画来模仿scroller,实现控件的滑动.

final ValueAnimator animator=ValueAnimator.ofInt(0,1).setDuration(1000);
animator.addUpdateListener(new AnimatorUpdateListener() {

@Override
public void onAnimationUpdate(ValueAnimator animation) {

//当前的比例
float fraction=animator.getAnimatedFraction();
button.scrollTo((int) (startX+(int)deltax*fraction), 0);
}
});
animator.start();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: