主頁 > 移動端開發 > Android基礎到進階UI祖父級 ViewGroup介紹+實用

Android基礎到進階UI祖父級 ViewGroup介紹+實用

2021-07-23 08:24:21 移動端開發

ViewGroup

ViewGroup是一個特殊的View,可以包含其他視圖(稱為子視圖),而ViewGroup是View的子類,所以ViewGroup可以當成普通的UI組件使用,ViewGroup是布局和視圖容器的基類,該類還定義了ViewGroup.LayoutParams用作布局引數基類的類,

由于ViewGroup的直接子類和間接子類比較多,上圖描述了展示了部分子類,下面把放在android.widget包下的ViewGroup的全部子類展示出來,

繼承關系該寫的基本差不多了,下面咱學習一個自定義ViewGroup,

自定義 ViewGroup

ViewGroup常用重寫方法:

onMeasure()

遍歷自己的子View對自己的每一個子View進行measure,絕大多數時候對子View的measure都可以直接用measureChild()這個方法來替代,確定子View的寬高和自己的寬高以后 再呼叫setMeasuredDimension將ViewGroup自身的寬和高傳給它的父View,才可以繼續寫onLayout()方法,

onSizeChanged()

在onMeasure()后執行,只有大小發生了變化才會執行onSizeChange(),

onLayout()

排列所有子View的位置,通過getChildCount()獲取所有子view,getChildAt獲取childview呼叫各自的layout(int l, int t, int r, int b)方法來排列自己,

onDraw()

自定義ViewGroup默認不會觸發onDraw方法,需要設定背景色或者setWillNotDraw(false)來手動觸發,

注意: ViewGroup的onLayout()方法是必須重寫的,而onDraw()方法默認是不會呼叫,如果想執行onDraw方法,可以通過下面兩種方法:

  • 1.設定透明背景:

    • 在建構式中:setBackgroundColor(Color.TRANSPARENT);
    • 在xml中:android:background="@color/transparent"
  • 2.在建構式中添加setWillNotDraw(false)不進行自行繪制View,

下面咱們寫一個簡單的栗子,先看效果圖,

1.創建CustomLayout繼承ViewGroup

/**
 * 撰寫自定義ViewGroup的示例,
 */
public class CustomLayout extends ViewGroup {
//    private int childHorizontalSpace = 20;
//    private int childVerticalSpace = 20;
    private int childHorizontalSpace;
    private int childVerticalSpace;
    //從代碼創建視圖時使用的簡單建構式,
    public CustomLayout(Context context) {
        super(context);
    }
    //從XML使用視圖時呼叫的建構式,
    public CustomLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray attrArray = context.obtainStyledAttributes(attrs, R.styleable.CustomLayout);
        if (attrArray != null) {
            childHorizontalSpace = attrArray.getDimensionPixelSize(R.styleable.CustomLayout_horizontalSpace, 12);
            childVerticalSpace = attrArray.getDimensionPixelSize(R.styleable.CustomLayout_verticalSpace, 12);
            MLog.e(getClass().getName(),"HorizontalSpace:"+childHorizontalSpace+"|VerticalSpace:"+childVerticalSpace);
            attrArray.recycle();
        }
        //此視圖是否自行繪制
        setWillNotDraw(false);
    }
    /**
     * 負責設定子控制元件的測量模式和大小 根據所有子控制元件設定自己的寬和高
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        MLog.e(getClass().getName(),"onMeasure");
        // 獲得它的父容器為它設定的測量模式和大小
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
        // 如果是warp_content情況下,記錄寬和高
        int width = 0;
        int height = 0;
        //記錄每一行的寬度,width不斷取最大寬度
        int lineWidth = 0;
        //每一行的高度,累加至height
        int lineHeight = 0;

        int count = getChildCount();
        int left = getPaddingLeft();
        int top = getPaddingTop();
        // 遍歷每個子元素
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            if (child.getVisibility() == GONE)
                continue;
            // 測量每一個child的寬和高
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            // 得到child的lp
            ViewGroup.LayoutParams lp = child.getLayoutParams();
            // 當前子空間實際占據的寬度
            int childWidth = child.getMeasuredWidth() + childHorizontalSpace;
            // 當前子空間實際占據的高度
            int childHeight = child.getMeasuredHeight() + childVerticalSpace;

            if (lp != null && lp instanceof MarginLayoutParams) {
                MarginLayoutParams params = (MarginLayoutParams) lp;
                childWidth += params.leftMargin + params.rightMargin;
                childHeight += params.topMargin + params.bottomMargin;
            }

            //如果加入當前child,則超出最大寬度,則的到目前最大寬度給width,類加height 然后開啟新行
            if (lineWidth + childWidth > sizeWidth - getPaddingLeft() - getPaddingRight()) {
                width = Math.max(lineWidth, childWidth);// 取最大的
                lineWidth = childWidth; // 重新開啟新行,開始記錄
                // 疊加當前高度,
                height += lineHeight;
                // 開啟記錄下一行的高度
                lineHeight = childHeight;
                child.setTag(new Location(left, top + height, childWidth + left - childHorizontalSpace, height + child.getMeasuredHeight() + top));
            } else {
                // 否則累加值lineWidth,lineHeight取最大高度
                child.setTag(new Location(lineWidth + left, top + height, lineWidth + childWidth - childHorizontalSpace + left, height + child.getMeasuredHeight() + top));
                lineWidth += childWidth;
                lineHeight = Math.max(lineHeight, childHeight);
            }
        }
        width = Math.max(width, lineWidth) + getPaddingLeft() + getPaddingRight();
        height += lineHeight;
        sizeHeight += getPaddingTop() + getPaddingBottom();
        height += getPaddingTop() + getPaddingBottom();
        setMeasuredDimension((modeWidth == MeasureSpec.EXACTLY) ? sizeWidth : width, (modeHeight == MeasureSpec.EXACTLY) ? sizeHeight : height);
    }
    /**
     * 記錄子控制元件的坐標
     */
    public class Location {
        public Location(int left, int top, int right, int bottom) {
            this.left = left;
            this.top = top;
            this.right = right;
            this.bottom = bottom;
        }
        public int left;
        public int top;
        public int right;
        public int bottom;
    }
    //計算當前View以及子View的位置
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        MLog.e(getClass().getName(),"onLayout");
        //獲取子View個數
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            //獲取子View
            View child = getChildAt(i);
            //判斷是否顯示
            if (child.getVisibility() == GONE)
                continue;
            //獲取子View的坐標
            Location location = (Location) child.getTag();
            //設定子View位置
            child.layout(location.left, location.top, location.right, location.bottom);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        MLog.e(getClass().getName(),"onSizeChanged");
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        MLog.e(getClass().getName(),"onDraw");
    }
}

2.使用自定義CustomLayout

<?xml version="1.0" encoding="utf-8"?>
<com.scc.demo.view.CustomLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="@dimen/dimen_20"
    custom:horizontalSpace="10dp"
    custom:verticalSpace="20dp">
    <!--一定記得添加前綴-->
    <TextView
        style="@style/TvStyle"
        android:text="破陣子·為陳同甫賦壯詞以寄" />

    <TextView
        style="@style/TvStyle"
        android:text="宋·辛棄疾" />

    <TextView
        style="@style/TvStyle"
        android:text="醉里挑燈看劍" />

    <TextView
        style="@style/TvStyle"
        android:text="夢回吹角連營" />

    <TextView
        style="@style/TvStyle"
        android:text="八百里分麾下炙" />

    <TextView
        style="@style/TvStyle"
        android:text="五十弦翻塞外聲" />

    <TextView
        style="@style/TvStyle"
        android:text="沙場秋點兵" />

    <TextView
        style="@style/TvStyle"
        android:text="馬作的盧飛快" />

    <TextView
        style="@style/TvStyle"
        android:text="弓如霹靂弦驚(增加點長度)" />

    <TextView
        style="@style/TvStyle"
        android:text="了卻君王天下事" />

    <TextView
        style="@style/TvStyle"
        android:text="贏得生前身后名" />

    <TextView
        style="@style/TvStyle"
        android:text="可憐白發生!" />
</com.scc.demo.view.CustomLayout>

自定義屬性

在app/src/main/res/values/attrs.xml中添加屬性

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomLayout">
        <attr name="verticalSpace" format="dimension" />
        <attr name="horizontalSpace" format="dimension" />
    </declare-styleable>
</resources>

使用自定義屬性

  • 在xml中使用

一定要添加:xmlns:test=”schemas.android.com/apk/res-aut…

<com.scc.demo.view.CustomLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="@dimen/dimen_20"
    custom:horizontalSpace="10dp"
    custom:verticalSpace="20dp">
</com.scc.demo.view.CustomLayout>
  • 在代碼中使用
 TypedArray attrArray = context.obtainStyledAttributes(attrs, R.styleable.CustomLayout);
        if (attrArray != null) {
            //引數1:獲取xml中設定的引數;引數2:獲取失敗2使用引數作為默認值
            childHorizontalSpace = attrArray.getDimensionPixelSize(R.styleable.CustomLayout_horizontalSpace, 12);
            childVerticalSpace = attrArray.getDimensionPixelSize(R.styleable.CustomLayout_verticalSpace, 12);
            MLog.e(getClass().getName(),"HorizontalSpace:"+childHorizontalSpace+"|VerticalSpace:"+childVerticalSpace);
            //TypedArray物件池的大小默認為5,使用時記得呼叫recyle()方法將不用的物件回傳至物件池來達到重用的目的,
            attrArray.recycle();
        }

寫到這里自定義ViewGroup基本完成,

ViewGroup屬性

ViewGroup的XML屬性以及相關方法

ViewGroup.LayoutParams

LayoutParams 被視圖用來告訴他們的父組件他們想要如何布局, 基本的 LayoutParams 類只是描述了視圖的寬度(android:layout_height)和高度(android:layout_width)的大小,對于每個維度,它可以指定以下之一:

  • a、MATCH_PARENT,這意味著視圖希望與其父視圖一樣大(減去填充)
  • b、WRAP_CONTENT,這意味著視圖希望足夠大以包含其內容(加上填充)
  • c、確切的數字

ViewGroup的不同子類都有LayoutParams的子類,例如,LinearLayout有自己的 LayoutParams子類,

ViewGroup.MarginLayoutParams

支持邊距的布局的每個子布局資訊, ViewGroup.MarginLayoutParams(子組件)的XML屬性及相關方法

ViewGroup寫到這里基本差不多了,更詳細的內容則通過后面的布局和視圖容器也深入了解,

最后

小編學習提升時,順帶從網上收集整理了一些 Android 開發相關的學習檔案、面試題、Android 核心筆記等等檔案,希望能幫助到大家學習提升,如有需要參考的可以直接去我 CodeChina地址:https://codechina.csdn.net/u012165769/Android-T3 訪問查閱,

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/289633.html

標籤:其他

上一篇:稍等,我手機幫你遠程除錯下代碼!

下一篇:Android的Kotlin的布局檔案里面的app:srcCompat提示:紅色波浪線

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【從零開始擼一個App】Dagger2

    Dagger2是一個IOC框架,一般用于Android平臺,第一次接觸的朋友,一定會被搞得暈頭轉向。它延續了Java平臺Spring框架代碼碎片化,注解滿天飛的傳統。嘗試將各處代碼片段串聯起來,理清思緒,真不是件容易的事。更不用說還有各版本細微的差別。 與Spring不同的是,Spring是通過反射 ......

    uj5u.com 2020-09-10 06:57:59 more
  • Flutter Weekly Issue 66

    新聞 Flutter 季度調研結果分享 教程 Flutter+FaaS一體化任務編排的思考與設計 詳解Dart中如何通過注解生成代碼 GitHub 用對了嗎?Flutter 團隊分享如何管理大型開源專案 插件 flutter-bubble-tab-indicator A Flutter librar ......

    uj5u.com 2020-09-10 06:58:52 more
  • Proguard 常用規則

    介紹 Proguard 入口,如何查看輸出,如何使用 keep 設定入口以及使用實體,如何配置壓縮,混淆,校驗等規則。

    ......

    uj5u.com 2020-09-10 06:59:00 more
  • Android 開發技術周報 Issue#292

    新聞 Android即將獲得類AirDrop功能:可向附近設備快速分享檔案 谷歌為安卓檔案管理應用引入可安全隱藏資料的Safe Folder功能 Android TV新主界面將顯示電影、電視節目和應用推薦內容 泄露的Android檔案暗示了傳說中的谷歌Pixel 5a與折疊屏新機 谷歌發布Andro ......

    uj5u.com 2020-09-10 07:00:37 more
  • AutoFitTextureView Error inflating class

    報錯: Binary XML file line #0: Binary XML file line #0: Error inflating class xxx.AutoFitTextureView 解決: <com.example.testy2.AutoFitTextureView android: ......

    uj5u.com 2020-09-10 07:00:41 more
  • 根據Uri,Cursor沒有獲取到對應的屬性

    Android: 背景:呼叫攝像頭,拍攝視頻,指定保存的地址,但是回傳的Cursor檔案,只有名稱和大小的屬性,沒有其他諸如時長,連ID屬性都沒有 使用 cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATIO ......

    uj5u.com 2020-09-10 07:00:44 more
  • Android連載29-持久化技術

    一、持久化技術 我們平時所使用的APP產生的資料,在記憶體中都是瞬時的,會隨著斷電、關機等丟失資料,因此android系統采用了持久化技術,用于存盤這些“瞬時”資料 持久化技術包括:檔案存盤、SharedPreference存盤以及資料庫存盤,還有更復雜的SD卡記憶體儲。 二、檔案存盤 最基本存盤方式, ......

    uj5u.com 2020-09-10 07:00:47 more
  • Android Camera2Video整合到自己專案里

    背景: Android專案里呼叫攝像頭拍攝視頻,原本使用的 MediaStore.ACTION_VIDEO_CAPTURE, 后來因專案需要,改成了camera2 1.Camera2Video 官方demo有點問題,下載后,不能直接整合到專案 問題1.多次拍攝視頻崩潰 問題2.雙擊record按鈕, ......

    uj5u.com 2020-09-10 07:00:50 more
  • Android 開發技術周報 Issue#293

    新聞 谷歌為Android TV開發者提供多種新功能 Android 11將自動填表功能整合到鍵盤輸入建議中 谷歌宣布Android Auto即將支持更多的導航和數字停車應用 谷歌Pixel 5只有XL版本 搭載驍龍765G且將比Pixel 4更便宜 [圖]Wear OS將迎來重磅更新:應用啟動時間 ......

    uj5u.com 2020-09-10 07:01:38 more
  • 海豚星空掃碼投屏 Android 接收端 SDK 集成 六步驟

    掃碼投屏,開放網路,獨占設備,不需要額外下載軟體,微信掃碼,發現設備。支持標準DLNA協議,支持倍速播放。視頻,音頻,圖片投屏。好點意思。還支持自定義基于 DLNA 擴展的操作動作。好像要收費,沒體驗。 這里簡單記錄一下集成程序。 一 跟目錄的build.gradle添加私有mevan倉庫 mave ......

    uj5u.com 2020-09-10 07:01:43 more
最新发布
  • 歡迎頁輪播影片

    如圖,引導開始,球從上落下,同時淡入文字,然后文字開始輪播,最后一頁時停止,點擊進入首頁。 在來看看效果圖。 重力球先不講,主要歡迎輪播簡單實作 首先新建一個類 TextTranslationXGuideView,用于影片展示 文本是類似的,最后會有個圖片箭頭影片,布局很簡單,就是一個 TextVi ......

    uj5u.com 2023-04-20 08:40:31 more
  • 【FAQ】關于華為推送服務因營銷訊息頻次管控導致服務通訊類訊息

    一. 問題描述 使用華為推送服務下發IM訊息時,下發訊息請求成功且code碼為80000000,但是手機總是收不到訊息; 在華為推送自助分析(Beta)平臺查看發現,訊息發送觸發了頻控。 二. 問題原因及背景 2023年1月05日起,華為推送服務對咨詢營銷類訊息做了單個設備每日推送數量上限管理,具體 ......

    uj5u.com 2023-04-20 08:40:11 more
  • 歡迎頁輪播影片

    如圖,引導開始,球從上落下,同時淡入文字,然后文字開始輪播,最后一頁時停止,點擊進入首頁。 在來看看效果圖。 重力球先不講,主要歡迎輪播簡單實作 首先新建一個類 TextTranslationXGuideView,用于影片展示 文本是類似的,最后會有個圖片箭頭影片,布局很簡單,就是一個 TextVi ......

    uj5u.com 2023-04-20 08:39:36 more
  • 【FAQ】關于華為推送服務因營銷訊息頻次管控導致服務通訊類訊息

    一. 問題描述 使用華為推送服務下發IM訊息時,下發訊息請求成功且code碼為80000000,但是手機總是收不到訊息; 在華為推送自助分析(Beta)平臺查看發現,訊息發送觸發了頻控。 二. 問題原因及背景 2023年1月05日起,華為推送服務對咨詢營銷類訊息做了單個設備每日推送數量上限管理,具體 ......

    uj5u.com 2023-04-20 08:39:13 more
  • iOS從UI記憶體地址到讀取成員變數(oc/swift)

    開發除錯時,我們發現bug時常首先是從UI顯示發現例外,下一步才會去定位UI相關連的資料的。XCode有給我們提供一系列debug工具,但是很多人可能還沒有形成一套穩定的除錯流程,因此本文嘗試解決這個問題,順便提出一個暴論:UI顯示例外問題只需要兩個步驟就能完成定位作業的80%: 定位例外 UI 組 ......

    uj5u.com 2023-04-19 09:16:23 more
  • FIDE重磅更新!性能飛躍!體驗有禮!

    FIDE 開發者工具重構升級啦!實作500%性能提升,誠邀體驗! 一直以來不少開發者朋友在社區反饋,在使用 FIDE 工具的程序中,時常會遇到諸如加載不及時、代碼預覽/渲染性能不如意的情況,十分影響開發體驗。 作為技術團隊,我們深知一件趁手的開發工具對開發者的重要性,因此,在2023年開年,FinC ......

    uj5u.com 2023-04-19 09:16:15 more
  • 游戲內嵌社區服務開放,助力開發者提升玩家互動與留存

    華為 HMS Core 游戲內嵌社區服務提供快速訪問華為游戲中心論壇能力,支持玩家直接在游戲內瀏覽帖子和交流互動,助力開發者擴展內容生產和觸達的場景。 一、為什么要游戲內嵌社區? 二、游戲內嵌社區的典型使用場景 1、游戲內打開論壇 您可以在游戲內繪制論壇入口,為玩家提供沉浸式發帖、瀏覽、點贊、回帖、 ......

    uj5u.com 2023-04-19 09:15:46 more
  • iOS從UI記憶體地址到讀取成員變數(oc/swift)

    開發除錯時,我們發現bug時常首先是從UI顯示發現例外,下一步才會去定位UI相關連的資料的。XCode有給我們提供一系列debug工具,但是很多人可能還沒有形成一套穩定的除錯流程,因此本文嘗試解決這個問題,順便提出一個暴論:UI顯示例外問題只需要兩個步驟就能完成定位作業的80%: 定位例外 UI 組 ......

    uj5u.com 2023-04-19 09:14:53 more
  • FIDE重磅更新!性能飛躍!體驗有禮!

    FIDE 開發者工具重構升級啦!實作500%性能提升,誠邀體驗! 一直以來不少開發者朋友在社區反饋,在使用 FIDE 工具的程序中,時常會遇到諸如加載不及時、代碼預覽/渲染性能不如意的情況,十分影響開發體驗。 作為技術團隊,我們深知一件趁手的開發工具對開發者的重要性,因此,在2023年開年,FinC ......

    uj5u.com 2023-04-19 09:14:08 more
  • 游戲內嵌社區服務開放,助力開發者提升玩家互動與留存

    華為 HMS Core 游戲內嵌社區服務提供快速訪問華為游戲中心論壇能力,支持玩家直接在游戲內瀏覽帖子和交流互動,助力開發者擴展內容生產和觸達的場景。 一、為什么要游戲內嵌社區? 二、游戲內嵌社區的典型使用場景 1、游戲內打開論壇 您可以在游戲內繪制論壇入口,為玩家提供沉浸式發帖、瀏覽、點贊、回帖、 ......

    uj5u.com 2023-04-19 09:08:34 more