一直對於這幾個概念沒有仔細區分過.
現在找個時間來分析一下這個幾個東西
scrollTo,scrollBy和Scroller
具體用法:
首先 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地址:https://download.csdn.net/detail/zmobs/6704237