android scrollTo,scrollBy,以及Scroller的用法示例


一直对于这几个概念没有仔细区分过.

现在找个时间来分析一下这个几个东西 

scrollTo,scrollByScroller 具体用法:

首先  scrollTo(x,y) 的参数是绝对坐标移动到x,y的位置区

		btnScroll = (Button) findViewById(R.id.button1);
		llMain = (LinearLayout) findViewById(R.id.ll_main);
//		zslMain = (ZScrollLayout) findViewById(R.id.ll_main);
		
		btnScroll.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
//				llMain.scrollBy(-50, 0);
				llMain.scrollTo(-50, 0);
//				zslMain.startSrcoll();
			}
		});



然后 scrollBy(x,y)是相对坐标,每一次scroll都会偏移相应的偏移量


		btnScroll = (Button) findViewById(R.id.button1);
		llMain = (LinearLayout) findViewById(R.id.ll_main);
//		zslMain = (ZScrollLayout) findViewById(R.id.ll_main);
		
		btnScroll.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				llMain.scrollBy(-50, 0);
//				llMain.scrollTo(-50, 0);
//				zslMain.startSrcoll();
			}
		});



ps: 特别要指出的一点是,scrollTo和scrollBy 都是由父控件调用后,父控件移动子控件的,这个可能表达的有点绕了,具体可以看代码


最后 Scroller 是滚动器,与scroolTo和scrollBy有较大的差别。Scroller的是专门用来计算渐变坐标的一个类,它并不负责UI的更新而只是纯粹的数据计算。

Scroller 的UI更新是通过调用上面的两个函数来实现的。


这个是自定义的父控件,需要 重写computeScroll函数,这个函数是在绘制动作是每次都会调用的,android也正是通过这种方式的渐变移动效果

public class ZScrollLayout extends LinearLayout {

	private Scroller mScroller;

	public ZScrollLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		mScroller = new Scroller(context);
	}

	public void startSrcoll() {
		mScroller.startScroll(10, 0, -300, 0, 5000);
		invalidate();
	}
	
	@Override
	public void computeScroll() {
		if (mScroller.computeScrollOffset()) {
			// 产生了动画效果,根据当前值 每次滚动一点
			scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
			// 此时同样也需要刷新View ,否则效果可能有误差
			postInvalidate();
		}
	}

}

接下来就是调用了:


		btnScroll = (Button) findViewById(R.id.button1);
//		llMain = (LinearLayout) findViewById(R.id.ll_main);
		zslMain = (ZScrollLayout) findViewById(R.id.ll_main);
		
		btnScroll.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				llMain.scrollBy(-50, 0);
				llMain.scrollTo(-50, 0);
//				zslMain.startSrcoll();
			}
		});




完整demo地址:http://download.csdn.net/detail/zmobs/6704237



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值