天天看點

面試官: 自定義View跟繪制流程相關知識點?(标準參考解答,值得收藏)最後

本文用于記錄自定義View的基礎步驟以及一些基礎的資訊,後期可能針對具體的點寫一些補充性的文章。

一 、View中關于四個構造函數參數

自定義View中View的構造函數有四個

//  主要是在java代碼中生命一個View時所調用,沒有任何參數,一個空的View對象
    public ChildrenView(Context context) {
        super(context);
    }
// 在布局檔案中使用該自定義view的時候會調用到,一般會調用到該方法
    public ChildrenView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }
//如果你不需要View随着主題變化而變化,則上面兩個構造函數就可以了
//下面兩個是與主題相關的構造函數
   public ChildrenView(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }
//
    public ChildrenView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }           

四個參數解釋:

context:上下文

AttributeSet attrs:從xml中定義的參數

intdefStyleAttr:主題中優先級最高的屬性

intdefStyleRes: 優先級次之的内置于View的style(這裡就是自定義View設定樣式的地方)

  • 多個地方定義屬性,優先級排序 Xml直接定義 > xml中style引用 > defStyleAttr>defStyleRes > theme直接定義 (參考文章: www.jianshu.com/p/7389287c0… )

二、自定義屬性說明

除了基本類型的不說 講一下其它幾個吧:

  • color :引用顔色
  • dimension: 引用字型大小
//定義
<attr name = "text_size" format = "dimension" />
//使用:
    app:text_size = "28sp" 
或者 
    app:text_size = "@android:dimen/app_icon_size"           
  • enum:枚舉值
//定義
    <attr name="orientation">
        <enum name="horizontal" value="0" />
        <enum name="vertical" value="1" />
    </attr>
//使用:
    app:orientation = "vertical"           
  • flags:标志 (位或運作) 主要作用=可以多個值
//定義
  <attr name="gravity">
            <flag name="top" value="0x01" />
            <flag name="bottom" value="0x02" />
            <flag name="left" value="0x04" />
            <flag name="right" value="0x08" />
            <flag name="center_vertical" value="0x16" />
    </attr>
// 使用
app:gravity = Top|left           
  • fraction:百分數:
//定義:
<attr name = "transparency" format = "fraction" />
//使用:
  app:transparency = "80%"            
  • reference:參考/引用某一資源ID
//定義:
 <attr name="leftIcon" format="reference" />
//使用:
app:leftIcon = "@drawable/圖檔ID"           
  • 混合類型:屬性定義時指定多種類型值
//屬性定義
 <attr name = "background" format = "reference|color" />
//使用
android:background = "@drawable/圖檔ID" 
//或者
android:background = "#FFFFFF"            

三、自定義控件類型

  • 自定義組合控件步驟

1. 自定義屬性

res/values

目錄下的

attrs.xml

檔案中

<resources>
<declare-styleable name="CustomView">
        <attr name="leftIcon" format="reference" />
        <attr name="state" format="boolean"/>
        <attr name="name" format="string"/>
    </declare-styleable>
</resources>           
2. 布局中使用自定義屬性

在布局中使用

<com.myapplication.view.CustomView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:leftIcon="@mipmap/ic_temp"
                app:name="溫度"
                app:state="false" />           
3. view的構造函數擷取自定義屬性
class DigitalCustomView : LinearLayout {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        LayoutInflater.from(context).inflate(R.layout.view_custom, this)
        var ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView)
        mIcon = ta.getResourceId(R.styleable.CustomView_leftIcon, -1) //左圖像
        mState = ta.getBoolean(R.styleable.DigitalCustomView_state, false)
        mName = ta.getString(R.styleable.CustomView_name)
        ta.recycle()
        initView()
    }

}           

上面給出大緻的代碼 記得擷取

context.obtainStyledAttributes(attrs, R.styleable.CustomView)

最後要調用

ta.recycle()

利用對象池回收ta加以複用

  • 繼承系統控件

就是繼承系統已經提供好給我們的控件例如TextView、LinearLayout等,分為View類型或者ViewGroup類型的兩種。主要根據業務需求進行實作,實作重寫的空間也很大 主要看需求。

比如需求 :在文字後面加個顔色背景

根據需要一般這種情況下我們是希望可以複用系統的

onMeaseur

onLayout

流程.直接複寫

onDraw

方法

class Practice02BeforeOnDrawView : AppCompatTextView {
    internal var paint = Paint(Paint.ANTI_ALIAS_FLAG)
    internal var bounds = RectF()

    constructor(context: Context) : super(context) {}

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {}

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}

    init {
        paint.color = Color.parseColor("#FFC107")
    }

    override fun onDraw(canvas: Canvas) {
        // 把下面的繪制代碼移到 super.onDraw() 的上面,就可以讓原主體内容蓋住你的繪制代碼了
        // (或者你也可以把 super.onDraw() 移到這段代碼的下面)
        val layout = layout
        bounds.left = layout.getLineLeft(1)
        bounds.right = layout.getLineRight(1)
        bounds.top = layout.getLineTop(1).toFloat()
        bounds.bottom = layout.getLineBottom(1).toFloat()
       //繪制方形背景
        canvas.drawRect(bounds, paint)
        super.onDraw(canvas)
    }
}           
這裡會涉及到畫筆

Paint()

、畫布

canvas

、路徑

Path

、繪畫順序等的一些知識點,後面再詳細說明
  • 直接繼承View

這種就是類似TextView等,不需要去輪訓子

View

隻需要根據自己的需求重寫

onMeasure()

onLayout()

onDraw()

等方法便可以,要注意點就是記得

Padding

等值要記得加入運算

private int getCalculateSize(int defaultSize, int measureSpec) {
        int finallSize = defaultSize;

        int mode = MeasureSpec.getMode(measureSpec);
        int size = MeasureSpec.getSize(measureSpec);
     //  根據模式對
        switch (mode) {
            case MeasureSpec.EXACTLY: {
              ...
                break;
            }
            case MeasureSpec.AT_MOST: {
                ...
                break;
            }
            case MeasureSpec.UNSPECIFIED: {
               ...
                break;
            }
        }
        return finallSize;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getCalculateSize(120, widthMeasureSpec);
        int height = getCalculateSize(120, heightMeasureSpec);
        setMeasuredDimension(width, height);
}

  //畫一個圓
    @Override
    protected void onDraw(Canvas canvas) {
        //調用父View的onDraw函數,因為View這個類幫我們實作了一些基本的而繪制功能,比如繪制背景顔色、背景圖檔等
        super.onDraw(canvas);
        int r = getMeasuredWidth() / 2;
        //圓心的橫坐标為目前的View的左邊起始位置+半徑
        int centerX = getLeft() + r;
        //圓心的縱坐标為目前的View的頂部起始位置+半徑
        int centerY = getTop() + r;

        Paint paint = new Paint();
        paint.setColor(Color.RED);
        canvas.drawCircle(centerX, centerY, r, paint);
    }
           
  • 直接繼承ViewGroup

類似實作LinearLayout等,可以去看那一下LinearLayout的實作 基本的你可能要重寫

onMeasure()

onLayout()

onDraw()

方法,這塊很多問題要處理包括輪訓

childView

的測量值以及模式進行大小邏輯計算等,這個篇幅過大後期加多個文章寫詳細的

這裡寫個簡單的需求,模仿

LinearLayout

的垂直布局

class CustomViewGroup :ViewGroup{

    constructor(context:Context):super(context)
    constructor(context: Context,attrs:AttributeSet):super(context,attrs){
            //可擷取自定義的屬性等
    }
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        //将所有的子View進行測量,這會觸發每個子View的onMeasure函數
        measureChildren(widthMeasureSpec, heightMeasureSpec)
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val widthSize = MeasureSpec.getSize(widthMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        val heightSize = MeasureSpec.getSize(heightMeasureSpec)
        val childCount = childCount
        if (childCount == 0) {
            //沒有子View的情況
            setMeasuredDimension(0, 0)
        } else {
            //如果寬高都是包裹内容
            if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
                //我們将高度設定為所有子View的高度相加,寬度設為子View中最大的寬度
                val height = getTotalHeight()
                val width = getMaxChildWidth()
                setMeasuredDimension(width, height)
            } else if (heightMode == MeasureSpec.AT_MOST) {
                //如果隻有高度是包裹内容
                //寬度設定為ViewGroup自己的測量寬度,高度設定為所有子View的高度總和
                setMeasuredDimension(widthSize, getTotalHeight())
            } else if (widthMode == MeasureSpec.AT_MOST) {//如果隻有寬度是包裹内容
                //寬度設定為子View中寬度最大的值,高度設定為ViewGroup自己的測量值
                setMeasuredDimension(getMaxChildWidth(), heightSize)

            }
        }
    /***
     * 擷取子View中寬度最大的值
     */
    private fun getMaxChildWidth(): Int {
        val childCount = childCount
        var maxWidth = 0
        for (i in 0 until childCount) {
            val childView = getChildAt(i)
            if (childView.measuredWidth > maxWidth)
                maxWidth = childView.measuredWidth

        }
        return maxWidth
    }

    /***
     * 将所有子View的高度相加
     */
    private fun getTotalHeight(): Int {
        val childCount = childCount
        var height = 0
        for (i in 0 until childCount) {
            val childView = getChildAt(i)
            height += childView.measuredHeight

        }

        return height
    }

    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        val count = childCount
        var currentHeight = t
        for (i in 0 until count) {
            val child = getChildAt(i)
            val h = child.measuredHeight
            val w = child.measuredWidth
            //擺放子view
            child.layout(l, currentHeight, l + w, currentHeight + h)
            currentHeight += h
        }
    }
}           
主要兩點 先

measureChildren()

輪訓周遊子

View

擷取寬高,并根據測量模式邏輯計算最後所有的控件的所需寬高,最後

setMeasuredDimension()

儲存一下 ###四、 View的繪制流程相關 最基本的三個相關函數

measure()

->

layout()

draw()

五、onMeasure()相關的知識點

1. MeasureSpec

MeasureSpec

View

的内部類,它封裝了一個

View

的尺寸,在

onMeasure()

當中會根據這個

MeasureSpec

的值來确定

View

的寬高。

MeasureSpec

的資料是

int

類型,有

32

位。 高兩位表示模式,後面

30

位表示大小

size

。則

MeasureSpec = mode+size

三種模式分别為:

EXACTLY

,

AT_MOST

UNSPECIFIED

EXACTLY

: (

match_parent

或者

精确資料值

)精确模式,對應的數值就是

MeasureSpec

當中的

size

AT_MOST

:(

wrap_content)

最大值模式,View的尺寸有一個最大值,

View

不超過

MeasureSpec

Size

UNSPECIFIED

:(一般系統使用)無限制模式,View設定多大就給他多大
//擷取測量模式
 val widthMode = MeasureSpec.getMode(widthMeasureSpec)
//擷取測量大小 
val widthSize = MeasureSpec.getSize(widthMeasureSpec)
//通過Mode和Size構造MeasureSpec
val measureSpec = MeasureSpec.makeMeasureSpec(size, mode);           

2. View #onMeasure()源碼

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
    }
    protected int getSuggestedMinimumWidth() {
        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
    }
    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
        boolean optical = isLayoutModeOptical(this);
        if (optical != isLayoutModeOptical(mParent)) {
            Insets insets = getOpticalInsets();
            int opticalWidth  = insets.left + insets.right;
            int opticalHeight = insets.top  + insets.bottom;

            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
            measuredHeight += optical ? opticalHeight : -opticalHeight;
        }
        setMeasuredDimensionRaw(measuredWidth, measuredHeight);
    }
    public static int getDefaultSize(int size, int measureSpec) {
        int result = size;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        switch (specMode) {
        case MeasureSpec.UNSPECIFIED:
            result = size;
            break;
        case MeasureSpec.AT_MOST:
        case MeasureSpec.EXACTLY:
            result = specSize;
            break;
        }
        return result;
    }
    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
        mMeasuredWidth = measuredWidth;
        mMeasuredHeight = measuredHeight;

        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
    }           
  • setMeasuredDimension(int measuredWidth, int measuredHeight) :用來設定View的寬高,在我們自定義View儲存寬高也會要用到。
  • getSuggestedMinimumWidth():當View沒有設定背景時,預設大小就是

    mMinWidth

    ,這個值對應

    Android:minWidth

    屬性,如果沒有設定時預設為0. 如果有設定背景,則預設大小為

    mMinWidth

    mBackground.getMinimumWidth()

    當中的較大值。
  • getDefaultSize(int size, int measureSpec):用來擷取View預設的寬高,在getDefaultSize()中對

    MeasureSpec.AT_MOST

    MeasureSpec.EXACTLY

    兩個的處理是一樣的,我們自定義

    View

    的時候 要對兩種模式進行處理。

3. ViewGroup中并沒有measure()也沒有onMeasure()

因為ViewGroup除了測量自身的寬高,還需要測量各個子

View

的寬高,不同的布局測量方式不同 (例如

LinearLayout

RelativeLayout

等布局),是以直接交由繼承者根據自己的需要去複寫。但是裡面因為子

View

的測量是相對固定的,是以裡面已經提供了基本的

measureChildren()

以及

measureChild()

來幫助我們對子

View

進行測量 這個可以看一下我另一篇文章:

LinearLayout # onMeasure()

LinearLayout onMeasure源碼閱讀

六、onLayout()相關

  1. View.java的onLayout方法是空實作:因為子View的位置,是由其父控件的onLayout方法來确定的。
  2. onLayout(int l, int t, int r, int b)中的參數l、t、r、b都是相對于其父 控件的位置。
  3. 自身的mLeft, mTop, mRight, mBottom都是相對于父控件的位置。

1. Android坐标系

2. 内部View坐标系跟點選坐标

3. 看一下View#layout(int l, int t, int r, int b)源碼

public void layout(int l, int t, int r, int b) {
        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
        }

        int oldL = mLeft;
        int oldT = mTop;
        int oldB = mBottom;
        int oldR = mRight;

        boolean changed = isLayoutModeOptical(mParent) ?
                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);

        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
            onLayout(changed, l, t, r, b);
   //   ....省略其它部分
    }
  private boolean setOpticalFrame(int left, int top, int right, int bottom) {
        Insets parentInsets = mParent instanceof View ?
                ((View) mParent).getOpticalInsets() : Insets.NONE;
        Insets childInsets = getOpticalInsets();
        return setFrame(
                left   + parentInsets.left - childInsets.left,
                top    + parentInsets.top  - childInsets.top,
                right  + parentInsets.left + childInsets.right,
                bottom + parentInsets.top  + childInsets.bottom);
    }
  protected boolean setFrame(int left, int top, int right, int bottom) {
        boolean changed = false;
    // ....省略其它部分
        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
            changed = true;
            int drawn = mPrivateFlags & PFLAG_DRAWN;
            int oldWidth = mRight - mLeft;
            int oldHeight = mBottom - mTop;
            int newWidth = right - left;
            int newHeight = bottom - top;
            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
            invalidate(sizeChanged);
            mLeft = left;
            mTop = top;
            mRight = right;
            mBottom = bottom;
            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
            mPrivateFlags |= PFLAG_HAS_BOUNDS;
            if (sizeChanged) {
                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
            }
            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
                mPrivateFlags |= PFLAG_DRAWN;
                invalidate(sizeChanged);
                invalidateParentCaches();
            }
            mPrivateFlags |= drawn;
            mBackgroundSizeChanged = true;
            mDefaultFocusHighlightSizeChanged = true;
            if (mForegroundInfo != null) {
                mForegroundInfo.mBoundsChanged = true;
            }
            notifySubtreeAccessibilityStateChangedIfNeeded();
        }
        return changed;
    }
           

四個參數

l、t、r、b

分别代表

View

的左、上、右、下四個邊界相對于其父

View

的距離。 在調用

onLayout(changed, l, t, r, b);

之前都會調用到

setFrame()

确定

View

在父容器當中的位置,指派給

mLeft

mTop

mRight

mBottom

。 在

ViewGroup#onLayout()

View#onLayout()

都是空實作,交給繼承者根據自身需求去定位

部分零散知識點:
  • getMeasureWidth()

    getWidth()

    getMeasureWidth()

    傳回的是

    mMeasuredWidth

    ,而該值是在

    setMeasureDimension()

    中的

    setMeasureDimensionRaw()

    中設定的。是以

    onMeasure()

    後的所有方法都能擷取到這個值。

    getWidth

    mRight-mLeft

    ,這兩個值,是在

    layout()

    setFrame()

    中設定的.

    getMeasureWidthAndState

    中有一句:

    This should be used during measurement and layout calculations only. Use {@link #getWidth()} to see how wide a view is after layout.

總結:隻有在測量過程中和布局計算時,才用

getMeasuredWidth()

。在layout之後,用

getWidth()

來擷取寬度

七、draw()繪畫過程

/*
         * Draw traversal performs several drawing steps which must be executed
         * in the appropriate order:
         *
         *      1\. Draw the background
         *      2\. If necessary, save the canvas' layers to prepare for fading
         *      3\. Draw view's content
         *      4\. Draw children
         *      5\. If necessary, draw the fading edges and restore layers
         *      6\. Draw decorations (scrollbars for instance)
         */           
上面是

draw()

裡面寫的繪畫順序。
  1. 繪制背景。
  2. 如果必要的話,儲存目前

    canvas

  3. 繪制

    View

    的内容
  4. 繪制子

    View

  5. 如果必要的話,繪畫邊緣重新儲存圖層
  6. 畫裝飾(例如滾動條)

1. 看一下View#draw()源碼的實作

public void draw(Canvas canvas) {
  // Step 1, draw the background, if needed
        int saveCount;

        if (!dirtyOpaque) {
            drawBackground(canvas);
        }

        // skip step 2 & 5 if possible (common case)
        final int viewFlags = mViewFlags;
        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
        if (!verticalEdges && !horizontalEdges) {
            // Step 3, draw the content
            if (!dirtyOpaque) onDraw(canvas);

            // Step 4, draw the children
            dispatchDraw(canvas);

            drawAutofilledHighlight(canvas);

            // Overlay is part of the content and draws beneath Foreground
            if (mOverlay != null && !mOverlay.isEmpty()) {
                mOverlay.getOverlayView().dispatchDraw(canvas);
            }

            // Step 6, draw decorations (foreground, scrollbars)
            onDrawForeground(canvas);

            // Step 7, draw the default focus highlight
            drawDefaultFocusHighlight(canvas);

            if (debugDraw()) {
                debugDrawFocus(canvas);
            }

            // we're done...
            return;
        }
}
           

由上面可以看到 先調用

drawBackground(canvas)

onDraw(canvas)

dispatchDraw(canvas)

onDrawForeground(canvas)

越是後面繪畫的越是覆寫在最上層。

drawBackground(canvas):畫背景,不可重寫

onDraw(canvas):畫主體

  • 代碼寫在super.onDraw()前:會被父類的onDraw覆寫
  • 代碼寫在super.onDraw()後:不會被父類的onDraw覆寫

dispatchDraw() :繪制子 View 的方法

  • 代碼寫在super.dispatchDraw(canvas)前:把繪制代碼寫在 super.dispatchDraw() 的上面,這段繪制就會在 onDraw() 之後、 super.dispatchDraw() 之前發生,也就是繪制内容會出現在主體内容和子 View 之間。而這個…… 其實和重寫 onDraw() 并把繪制代碼寫在 super.onDraw() 之後的做法,效果是一樣的。
  • 代碼寫在super.dispatchDraw(canvas)後:隻要重寫 dispatchDraw(),并在 super.dispatchDraw() 的下面寫上你的繪制代碼,這段繪制代碼就會發生在子 View 的繪制之後,進而讓繪制内容蓋住子 View 了。

onDrawForeground(canvas):包含了滑動邊緣漸變和滑動條跟前景

一般來說,一個 View(或 ViewGroup)的繪制不會這幾項全都包含,但必然逃不出這幾項,并且一定會嚴格遵守這個順序。例如通常一個 LinearLayout 隻有背景和子 View,那麼它會先繪制背景再繪制子 View;一個 ImageView 有主體,有可能會再加上一層半透明的前景作為遮罩,那麼它的前景也會在主體之後進行繪制。需要注意,前景的支援是在 Android 6.0(也就是 API 23)才加入的;之前其實也有,不過隻支援 FrameLayout,而直到 6.0 才把這個支援放進了 View 類裡。

2. 注意事項

2.1 在 ViewGroup 的子類中重寫除 dispatchDraw() 以外的繪制方法時,可能需要調用 setWillNotDraw(false);

出于效率的考慮,ViewGroup 預設會繞過 draw() 方法,換而直接執行 dispatchDraw(),以此來簡化繪制流程。是以如果你自定義了某個 ViewGroup 的子類(比如 LinearLayout)并且需要在它的除 dispatchDraw() 以外的任何一個繪制方法内繪制内容,你可能會需要調用 View.setWillNotDraw(false) 這行代碼來切換到完整的繪制流程(是「可能」而不是「必須」的原因是,有些 ViewGroup 是已經調用過 setWillNotDraw(false) 了的,例如 ScrollView)。

2.2 在重寫的方法有多個選擇時,優先選擇 onDraw()

一段繪制代碼寫在不同的繪制方法中效果是一樣的,這時你可以選一個自己喜歡或者習慣的繪制方法來重寫。但有一個例外:如果繪制代碼既可以寫在 onDraw() 裡,也可以寫在其他繪制方法裡,那麼優先寫在 onDraw() ,因為 Android 有相關的優化,可以在不需要重繪的時候自動跳過 onDraw() 的重複執行,以提升開發效率。享受這種優化的隻有 onDraw() 一個方法。

八、在Activity中擷取View的寬高的幾種方式

Activity 擷取 view 的寬高, 在 onCreate , onResume 等方法中擷取到的都是0, 因為 View 的測量過程并不是和 Activity 的聲明周期同步執行的

1. view.post post 可以将一個 runnable 投遞到消息隊列的尾部,然後等待 Looper 調用此 runnable 的時候, View 也已經初始化好了

view.post(new Runnable() {
            @Override
            public void run() {
                int width = view.getMeasuredWidth();
                int height = view.getMeasuredHeight(); 
            }
        });           

2. ViewTreeObserver 使用 addOnGlobalLayoutListener 接口, 當 view 樹的狀态發生改變或者 View 樹内部的 view 的可見性發生改變時, onGlobalLayout 都會被調用, 需要注意的是, onGlobalLayout 方法可能被調用多次, 代碼如下:

view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                int width = view.getMeasuredWidth();
                int height = view.getMeasuredHeight();
            }
        });           

3. onWindowFocusChanged 這個方法的含義是 View 已經初始化完畢了, 寬高已經準備好了, 需要注意的就是這個方法可能會調用多次, 在 Activity

onResume

onPause

的時候都會調用, 也會有多次調用的情況

@Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);
        if(hasWindowFocus){
            int width = view.getMeasuredWidth();
            int height = view.getMeasuredHeight();
        }
    }           

節選自:未揚帆的小船

https://juejin.im/post/5dde44dc5188250e8b235d83

最後

題外話,雖然我在阿裡工作時間不長,但也指導過不少同行。很少跟大家一起探讨,今年春節受武漢新型冠狀病毒影響,大家都隻能在家辦公學習,待疫情過去,大家重歸工作崗位,面試和崗位流動多起來,是以充分利用這段時間複習,未來在尋找工作過程中占領有利位置就顯得尤為重要了。

在這裡我分享兩本由我們阿裡同僚總結《Android面試指導》,以及《Android架構師面試題精編解析大全》兩本電子書分享給讀者,需要的朋友,點選下方連結,前往免費領取!

下載下傳位址:

https://shimo.im/docs/3Tvytq686Yyv83KX/read

繼續閱讀