Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自訂控件系列:從源碼理解 View 的顯示與滾動

編輯:關於 Android 程式設計

我們在 Android 設備上所看到的畫面,其實與底層的繪製機制關係密切。本文從源碼出發,帶你理解 View 是如何被繪製,以及它又是如何控制顯示位置的。

理解 View 的顯示區域

先來看一張示意圖:

整個設備的可見區域其實就是中間那塊螢幕,而在它的上下左右其實都還有內容存在。那麼 Android 系統是如何控制顯示位置的呢?

scrollTo 與 scrollBy

打開 View 類別的源碼,可以找到這兩個關鍵方法(以下摘自 5.0 源碼):

public void scrollTo(int x, int y) {
    if (mScrollX != x || mScrollY != y) {
        int oldX = mScrollX;
        int oldY = mScrollY;
        mScrollX = x;
        mScrollY = y;
        invalidateParentCaches();
        onScrollChanged(mScrollX, mScrollY, oldX, oldY);
        if (!awakenScrollBars()) {
            postInvalidateOnAnimation();
        }
    }
}
public void scrollBy(int x, int y) {
    scrollTo(mScrollX + x, mScrollY + y);
}

可以看到 scrollBy 其實只是呼叫 scrollTo。而 scrollTo 中最關鍵的一句就是 postInvalidateOnAnimation(),它會回呼 onDraw() 方法,在其中繪製可見區域。翻開 View 的 draw() 方法,其繪製順序大致為:先畫背景,接著處理淡化層、繪製內容、繪製子檢視,最後畫上捲軸等裝飾。核心邏輯是取出 mScrollX 與 mScrollY,再透過 canvas 的 translate 平移繪圖,於是我們就看到視圖裡顯示的內容了。

實例演示

我們直接寫一段簡單的程式碼來理解。首先在 Activity 的 onCreate 中初始化一個超大視圖:

LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setLayoutParams(new LayoutParams(2000, 2000)); // 刻意設大一點方便測試
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
TextView textView1 = new TextView(this);
textView1.setText("hello i am text 1");
textView1.setLayoutParams(new LayoutParams(1000, 2000));
linearLayout.addView(textView1);
TextView textView2 = new TextView(this);
textView2.setText("hello i am text 2");
textView2.setLayoutParams(new LayoutParams(1000, 2000));
linearLayout.addView(textView2);
setContentView(linearLayout);

跑起來會發現 textView2 根本沒顯示出來,因為它超出了螢幕範圍:

這時只要補上一句 scrollTo,把視圖向左滾動:

linearLayout.scrollTo(1000, 0); // 新增這一句

textView2 就完整顯示出來了。可見 scrollTo 與 scrollBy 這兩個方法在後續的 UI 控件開發中會被頻繁使用,從源頭理解它們,能幫助我們更順利地掌握往後的內容。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved