[Android FrameWork 6.0源碼學習] ViewGroup的addView函數分析

来源:http://www.cnblogs.com/kezhuang/archive/2017/06/10/6972952.html
-Advertisement-
Play Games

Android中整個的View的組裝是採用組合模式。 ViewGroup就相當與樹根,各種Layout就相當於枝幹,各種子View,就相當於樹葉。 至於View類。我們就當它是個種子吧。哈哈! ViewGroup屬於樹根,可以生長數很多枝幹(繼承自定義Layout)而枝幹上有可以長出很多葉子(Tex ...


Android中整個的View的組裝是採用組合模式。

ViewGroup就相當與樹根,各種Layout就相當於枝幹,各種子View,就相當於樹葉。

至於View類。我們就當它是個種子吧。哈哈!

ViewGroup屬於樹根,可以生長數很多枝幹(繼承自定義Layout)而枝幹上有可以長出很多葉子(TextView,ImageVIew......)

好,閑話少敘,接下來步入正題!

首先,關於View的操作方法,被定義在一個叫做ViewManager的介面中,介面中還有兩個方法,分別是移除和更新,這次主要分析addView

public interface ViewManager
    {
        /**
         * Assign the passed LayoutParams to the passed View and add the view to the window.
         * <p>Throws {@link android.view.WindowManager.BadTokenException} for certain programming
         * errors, such as adding a second view to a window without removing the first view.
         * <p>Throws {@link android.view.WindowManager.InvalidDisplayException} if the window is on a
         * secondary {@link Display} and the specified display can't be found
         * (see {@link android.app.Presentation}).
         * @param view The view to be added to this window.
         * @param params The LayoutParams to assign to view.
         */
        public void addView(View view, ViewGroup.LayoutParams params);
        public void updateViewLayout(View view, ViewGroup.LayoutParams params);
        public void removeView(View view)
  }

 addView在ViewGroup中實現,接下來貼出代碼進行分析

    public void addView(View child, LayoutParams params) {
        addView(child, -1, params);
    }

這個方法中調用了自身的addView方法,並且多傳遞了一個-1,這個-1是View的索引,要插入的位置

    public void addView(View child, int index, LayoutParams params) {
        if (DBG) {
            System.out.println(this + " addView");
        }

        if (child == null) {
            throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup");
        }

        // addViewInner() will call child.requestLayout() when setting the new LayoutParams
        // therefore, we call requestLayout() on ourselves before, so that the child's request
        // will be blocked at our level
        requestLayout();
        invalidate(true);
        addViewInner(child, index, params, false);
    }

 

 這個方法先是重繪了一下佈局,然後調用了addViewInner(child, index, params, false);方法,來把View插入到相應的位置

    private void addViewInner(View child, int index, LayoutParams params,
            boolean preventRequestLayout) {

        if (mTransition != null) {
            // Don't prevent other add transitions from completing, but cancel remove
            // transitions to let them complete the process before we add to the container
            mTransition.cancel(LayoutTransition.DISAPPEARING);
        }

        if (child.getParent() != null) {
            throw new IllegalStateException("The specified child already has a parent. " +
                    "You must call removeView() on the child's parent first.");
        }

        if (mTransition != null) {
            mTransition.addChild(this, child);
        }

        if (!checkLayoutParams(params)) {
            params = generateLayoutParams(params);
        }

        if (preventRequestLayout) {
            child.mLayoutParams = params;
        } else {
            child.setLayoutParams(params);
        }

        if (index < 0) {
            index = mChildrenCount;
        }

        //ViewGroup用一個View類型的數組去維護下邊的子view,這個方法就是把view添加到響應的位置上
        addInArray(child, index);

        //綁定插入的view的父容器為當前group
        // tell our children
        if (preventRequestLayout) {
            child.assignParent(this);
        } else {
            child.mParent = this;
        }

        if (child.hasFocus()) {
            requestChildFocus(child, child.findFocus());
        }

        AttachInfo ai = mAttachInfo;
        if (ai != null && (mGroupFlags & FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW) == 0) {
            boolean lastKeepOn = ai.mKeepScreenOn;
            ai.mKeepScreenOn = false;
            child.dispatchAttachedToWindow(mAttachInfo, (mViewFlags&VISIBILITY_MASK));
            if (ai.mKeepScreenOn) {
                needGlobalAttributesUpdate(true);
            }
            ai.mKeepScreenOn = lastKeepOn;
        }

        if (child.isLayoutDirectionInherited()) {
            child.resetRtlProperties();
        }

        dispatchViewAdded(child);

        if ((child.mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE) {
            mGroupFlags |= FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE;
        }

        if (child.hasTransientState()) {
            childHasTransientStateChanged(child, true);
        }

        if (child.getVisibility() != View.GONE) {
            notifySubtreeAccessibilityStateChangedIfNeeded();
        }

        if (mTransientIndices != null) {
            final int transientCount = mTransientIndices.size();
            for (int i = 0; i < transientCount; ++i) {
                final int oldIndex = mTransientIndices.get(i);
                if (index <= oldIndex) {
                    mTransientIndices.set(i, oldIndex + 1);
                }
            }
        }
    }

 

 這個方法先檢查一下LayoutParams,看看插入的該view是否存在長寬,如果沒有就生成一個預設的LayoutParams

然後判斷index是否小於0,小於0就賦值為當前容器中的個數,代表插入到最後一項

隨後就調用addInArray方法,來插入View到當前ViewGroup中,插入完成後給該view綁定一下父容器(getParent的值)

隨後就是一些焦點,監聽的分發,我們仔細分析一下插入方法就好了,就是addInArray

 

   private void addInArray(View child, int index) {
        View[] children = mChildren;
        final int count = mChildrenCount;
        final int size = children.length;
        if (index == count) {
            if (size == count) {
                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
                System.arraycopy(children, 0, mChildren, 0, size);
                children = mChildren;
            }
            children[mChildrenCount++] = child;
        } else if (index < count) {
            if (size == count) {
                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
                System.arraycopy(children, 0, mChildren, 0, index);
                System.arraycopy(children, index, mChildren, index + 1, count - index);
                children = mChildren;
            } else {
                System.arraycopy(children, index, children, index + 1, count - index);
            }
            children[index] = child;
            mChildrenCount++;
            if (mLastTouchDownIndex >= index) {
                mLastTouchDownIndex++;
            }
        } else {
            throw new IndexOutOfBoundsException("index=" + index + " count=" + count);
        }
    }

 

 

 

mChildren是ViewGroup中的一個View類型的數組,裡邊存放了該Group下的所有子View

ARRAY_CAPACITY_INCREMENT這個常量的值是12

首先判斷一下mChildren的位置還是否充足,不充足就繼續擴充12個位置出來,copy源數組內容進到新數組裡,然後再把本次要添加的view放到最後

如果index比count小,說明是插入操作,也是先判斷位置是否充足,不充足就擴充並且copy到index處,然後在把剩下的copy到index+1到末尾

這樣就把index位置空了出來。就完成了插入操作

插入完成後,系統會重繪界面,你就可以看到你插入的view了。

 

addView這個方法就分析完了,有什麼疑問就可以指出來,錯誤也一樣。共同學習共同進步。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • UX瀏覽服務是為了加速瀏覽網頁而開發的瀏覽服務,它解決了WebView的一系列問題,它能夠在網路差的情況下快速的瀏覽,比webview快一倍以上,是webview的優化代替方案。它擁有完善的緩存管理策略,經過優化的載入順序,廣告攔截引擎。 這次更新我們修複大量問題: 1. 緩存加速、DNS加速、弱網 ...
  • 一、在app/src/main/res下有 AndroidManifest.xml打開,打開後如下圖1 二、日誌工具log log.v() log.d() log.i() log.w() log.e() 在下圖中 中存在輸出 ...
  • 先看效果: 參照Android的實現方式用RadioButton來實現,但是Uwp的RadioButton並沒有安卓的Selector選擇器 下麵是一個比較簡單的實現,如果有同學有更好的實現,歡迎留言,讓我們共同進步。 1、首先自定義一個RadioImageButton控制項,並定義幾個依賴屬性,代碼 ...
  • 1.Android DVM(Dalvik VM)的進程和Linux的進程, 應用程式的進程是同一個概念嗎? DVM(Dalvik VM)指dalvik的虛擬機。每一個Android應用程式都在它自己的進程中運行,都擁有一個獨立的Dalvik虛擬機實例。而每一個DVM都是在Linux 中的一個進程,所 ...
  • iOS CAShapeLayer、CADisplayLink 實現波浪動畫效果 效果圖 代碼已上傳 GitHub:https://github.com/Silence GitHub/CoreAnimationDemo 可以自定義波浪高度、寬度、速度、方向、漸變速度、水的深度等參數。 實現原理 波浪的 ...
  • 作者:Antonio Leiva 時間:Jun 6, 2017 原文鏈接:https://antonioleiva.com/interfaces-kotlin/ 與Java相比,Kotlin介面允許你重用更多的代碼。 原因非常簡單:你能夠向你的介面加代碼。如果你已經試用過Java8,這非常類似。 能 ...
  • 瞭解這一章節,需要先瞭解LayoutInflater這個工具類,我以前分析過:http://www.cnblogs.com/kezhuang/p/6978783.html Window是Activity類中的一個全局變數,Window的作用是輔助Activity(也有可能是其他組件,本章拿Activ ...
  • LayoutInflater是用來解析XML佈局文件,然後生成對象的ViewTree的工具類。是這個工具類的存在,才能讓我們寫起Layout來那麼省勁。 我們接下來進去刨析,看看裡邊的奧秘 我們在使用這個類的時候,通常都是像上面這樣寫,首先通過from函數獲取對象,在調用inflate方法,來生成相 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...