1. 程式人生 > >Android中滑屏初探 ---- scrollTo 以及 scrollBy方法使用說明

Android中滑屏初探 ---- scrollTo 以及 scrollBy方法使用說明

         今天給大家介紹下Android中滑屏功能的一個基本實現過程以及原理初探,最後給大家重點講解View檢視中scrollTo 與

   scrollBy這兩個函式的區別 。

        首先 ,我們必須明白在Android View檢視是沒有邊界的,Canvas是沒有邊界的,只不過我們通過繪製特定的View時對

   Canvas物件進行了一定的操作,例如 : translate(平移)、clipRect(剪下)等,以便達到我們的對該Canvas物件繪製的要求 ,

   我們可以將這種無邊界的檢視稱為“檢視座標”-----它不受物理螢幕限制。通常我們所理解的一個Layout佈局檔案只是該視

   圖的顯示區域,超過了這個顯示區域將不能顯示到父檢視的區域中 ,對應的,我們可以將這種有邊界的檢視稱為“佈局座標

    ------ 父檢視給子檢視分配的佈局(layout)大小。而且, 一個檢視的在螢幕的起始座標位於檢視座標起始處,如下圖所示。

         這麼來說吧 ,世界本是無邊無界的,可是我們的眼睛我們的心約束了我們所看到的“世界” 。

       如下所示:

            

              黑色框框表示該子檢視的佈局座標, 褐色框框表示該子檢視的檢視座標--該座標是無限的,超過了父檢視給子檢視

       規定的區域後,不再顯示該超出內容。

          那麼下面的問題就是:如何將我們的檢視的任意座標能顯示到該檢視的中心座標上呢? 由於該佈局位置是隻能顯示特定的

  一塊檢視內容 ,因此我們需要通過scrollTo()或者scrollBy()方法將我們期望的檢視“滾動”至佈局座標上。

      在View.java中提供了了如下兩個變數以及相應的屬性方法去讀取滾動值 ,如下: View.java類中

/**
	 * The offset, in pixels, by which the content of this view is scrolled
	 * horizontally.
	 * {@hide}
	 */
	protected int mScrollX;   //該檢視內容相當於檢視起始座標的偏移量   , X軸 方向
	/**
	 * The offset, in pixels, by which the content of this view is scrolled
	 * vertically.
	 * {@hide}
	 */
	protected int mScrollY;   //該檢視內容相當於檢視起始座標的偏移量   , Y軸方向

	/**
     * Return the scrolled left position of this view. This is the left edge of
     * the displayed part of your view. You do not need to draw any pixels
     * farther left, since those are outside of the frame of your view on
     * screen.
     *
     * @return The left edge of the displayed part of your view, in pixels.
     */
    public final int getScrollX() {
        return mScrollX;
    }

    /**
     * Return the scrolled top position of this view. This is the top edge of
     * the displayed part of your view. You do not need to draw any pixels above
     * it, since those are outside of the frame of your view on screen.
     *
     * @return The top edge of the displayed part of your view, in pixels.
     */
    public final int getScrollY() {
        return mScrollY;
    }

      注意,所謂的“by which the content of this view is scrolled”表示該偏移量只針對於該View中onDraw()方法裡的

     提示:下文中提到的當前檢視內容是在繪製在佈局座標處的內容。

     public void scrollTo(int x, int y)

              說明:在當前檢視內容偏移至(x , y)座標處,即顯示(可視)區域位於(x , y)座標處。

        方法原型為: View.java類中

    /**
     * Set the scrolled position of your view. This will cause a call to
     * {@link #onScrollChanged(int, int, int, int)} and the view will be
     * invalidated.
     * @param x the x position to scroll to
     * @param y the y position to scroll to
     */
    public void scrollTo(int x, int y) {
    	//偏移位置發生了改變
        if (mScrollX != x || mScrollY != y) {
            int oldX = mScrollX;
            int oldY = mScrollY;
            mScrollX = x;  //賦新值,儲存當前便宜量
            mScrollY = y;
            //回撥onScrollChanged方法
            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
            if (!awakenScrollBars()) {
                invalidate();  //一般都引起重繪
            }
        }
    }
    

public void scrollBy(int x, int y)    

            說明:在當前檢視內容繼續偏移(x , y)個單位,顯示(可視)區域也跟著偏移(x,y)個單位。

        方法原型為: View.java類中

  /**
     * Move the scrolled position of your view. This will cause a call to
     * {@link #onScrollChanged(int, int, int, int)} and the view will be
     * invalidated.
     * @param x the amount of pixels to scroll by horizontally
     * @param y the amount of pixels to scroll by vertically
     */
    // 看出原因了吧 。。 mScrollX 與 mScrollY 代表我們當前偏移的位置 , 在當前位置繼續偏移(x ,y)個單位
    public void scrollBy(int x, int y) {
        scrollTo(mScrollX + x, mScrollY + y);
    }

       第一個小Demo非常簡單 ,大家重點理解與掌握scrollTo() 與 scrollBy()函式的用法和區別。

       第二個小Demo則有了Launcher的模樣,能夠左右切換螢幕 。實現功能如下: 採用了一個自定義ViewGroup,該ViewGroup

   物件包含了3個LinearLayout子檢視,並且以一定的佈局座標(由layout()方法指定)顯示在ViewGroup上。 接下來,即可呼叫該

   ViewGroup物件的scrollTo或者scrollBy()方法切換指定檢視內容了,即切換螢幕。 呵呵 ,挺好玩的吧 。

       截圖如下:

                           

       自定義ViewGroup如下:

//自定義ViewGroup , 包含了三個LinearLayout控制元件,存放在不同的佈局位置,通過scrollBy或者scrollTo方法切換
public class MultiViewGroup extends ViewGroup {

	private Context mContext;

	private static String TAG = "MultiViewGroup";

	public MultiViewGroup(Context context) {
		super(context);
		mContext = context;
		init();
	}

	public MultiViewGroup(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		init();
	}

	private void init() {
		// 初始化3個 LinearLayout控制元件
		LinearLayout oneLL = new LinearLayout(mContext);
		oneLL.setBackgroundColor(Color.RED);
        addView(oneLL);
		
		LinearLayout twoLL = new LinearLayout(mContext);
		twoLL.setBackgroundColor(Color.YELLOW);
		addView(twoLL);
		
		LinearLayout threeLL = new LinearLayout(mContext);
		threeLL.setBackgroundColor(Color.BLUE);
		addView(threeLL);
	}

	// measure過程
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

		Log.i(TAG, "--- start onMeasure --");

		// 設定該ViewGroup的大小
		int width = MeasureSpec.getSize(widthMeasureSpec);
		int height = MeasureSpec.getSize(heightMeasureSpec);
		setMeasuredDimension(width, height);

		int childCount = getChildCount();
		Log.i(TAG, "--- onMeasure childCount is -->" + childCount);
		for (int i = 0; i < childCount; i++) {
			View child = getChildAt(i);
			// 設定每個子檢視的大小 , 即全屏
			child.measure(MultiScreenActivity.screenWidth, MultiScreenActivity.scrrenHeight);
		}
	}

	// layout過程
	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		// TODO Auto-generated method stub
		Log.i(TAG, "--- start onLayout --");
		int startLeft = 0; // 每個子檢視的起始佈局座標
		int startTop = 10; // 間距設定為10px 相當於 android:marginTop= "10px"
		int childCount = getChildCount();
		Log.i(TAG, "--- onLayout childCount is -->" + childCount);
		for (int i = 0; i < childCount; i++) {
			View child = getChildAt(i);
			child.layout(startLeft, startTop, 
					startLeft + MultiScreenActivity.screenWidth, 
					startTop + MultiScreenActivity.scrrenHeight);
			startLeft = startLeft + MultiScreenActivity.screenWidth ; //校準每個子View的起始佈局位置
			//三個子檢視的在螢幕中的分佈如下 [0 , 320] / [320,640] / [640,960]
		}
	}

}

          PS  :大家可以分別給這幾個LinearLayout試著新增幾個子View,例如TextView, Button等

        至於Launcher上滑屏功能的實現,我嘗試著去掌握,可能天資愚鈍吧,對Scoller類很是感冒,現今還沒有掌握好,不過在此

   給大家推薦幾個不錯的學習資源 。 以後有需要的話,還是採用拿來主義吧。 囧

            補充(收回上面一段話,- -):關於如何實現觸控滑屏---- 仿Launcher滑屏以及Scoller類的使用,請參閱我的