Android自定義View之繼承自View後的wrap_content屬性不生效的解決

關於自定義View,建議大家最好繼承自Android已經實現過的View,比如ImageView和TextView,這樣比較簡單,而且各種屬性都能生效,比如match_parent和wrap_content等屬性。
但是當你開發的自定義View是繼承自View的話,那就需要考慮自己實現wrap_content屬性了,如果不自己實現的話,你的wrap_content和match_parent是一樣的效果。

關於wrap_content不生效的原因,要從源碼來分析onMeasure的過程

假設佈局文件

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/> 高度是wrap_content,但是卻填充了父容器

</FrameLayout>

android.view.View的測量源碼

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
    }

    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;
    }

從上面的代碼可以看出,android.view.View在measure時,FrameLayout會傳入MeasureSpec.AT_MOST(爲什麼會出入AT_MOST呢,這裏不做分析),但是View居然不關注自身的屬性,而是一律使用FrameLayout給的最大可用高度specSize,這就導致了View填充FrameLayout的現象。

那再來看看一個TextView是如何measure的

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content" 寬度是wrap_content,此時寬度真的爲0px
        android:layout_height="match_parent"/> 

</FrameLayout>

android.view.TextView的部分代碼


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        ......
        if (widthMode == MeasureSpec.EXACTLY) {
            // Parent has told us how big to be. So be it.
            width = widthSize;
        } else {
            ......
            // 根據內容計算出width
            width = Math.max(width, getSuggestedMinimumWidth());
            if (widthMode == MeasureSpec.AT_MOST) {
                width = Math.min(widthSize, width); // 在AT_MOST的情況下,並不是直接使用最大specSize
            }
        }
        ......

繼承自View的wrap_content屬性的measure解決方案。


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        ViewGroup.LayoutParams layoutParams = getLayoutParams();

        int width = measureSelfWidthOrHeight(MeasureSpec.getMode(widthMeasureSpec),
                MeasureSpec.getSize(widthMeasureSpec),
                getPaddingLeft() + getPaddingRight(),
                layoutParams.width, getSuggestedMinimumWidth());

        int height = measureSelfWidthOrHeight(MeasureSpec.getMode(heightMeasureSpec),
                MeasureSpec.getSize(heightMeasureSpec),
                getPaddingTop() + getPaddingBottom(),
                layoutParams.height, getSuggestedMinimumHeight());

        setMeasuredDimension(width, height);

        for (int i = 0; i < getChildCount(); i++) {
            if (getChildAt(i).getVisibility() != GONE) {
                getChildAt(i).measure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(width), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(height), MeasureSpec.EXACTLY));
            }
        }
    }

    private int measureSelfWidthOrHeight(int heightMode, int heightSize, int extraHeight, int layoutParamHeight, int suggestedMinHeight) {
        int height = 0;
        switch (heightMode) {
            case MeasureSpec.EXACTLY: // 高度是確定的
                height = heightSize;
                break;
            case MeasureSpec.AT_MOST: // AT_MOST一般是因爲設置了wrap_content屬性獲得,但不全是這樣,所以的全面考慮layoutParams的3種不同情況
                if (layoutParamHeight == LayoutParams.WRAP_CONTENT) {
                    int disert = Math.max(suggestedMinHeight, extraHeight);
                    height = Math.min(disert, heightSize);
                } else if (layoutParamHeight == LayoutParams.MATCH_PARENT) {
                    height = heightSize;
                } else {
                    height = Math.min(layoutParamHeight + extraHeight, heightSize);
                }
                break;
            case MeasureSpec.UNSPECIFIED:
                if (layoutParamHeight == LayoutParams.WRAP_CONTENT || layoutParamHeight == LayoutParams.MATCH_PARENT) {
                    height = Math.max(suggestedMinHeight, extraHeight);
                } else {
                    height = layoutParamHeight + extraHeight;
                }
                break;
            default:
        }
        return height;
    }

MeasureSpecMode

關於MeasureSpecMode的3種狀態:UNSPECIFIED,EXACTLY,AT_MOST。
常使用的有EXACTLY和AT_MOST。

  • EXACTLY這種情形是子View設置了明確的大小時,父容器直接告訴子View一個大小。
  • AT_MOST 在父容器的大小確定,但子View設置了wrap_content時,子View將不能超過父容器的大小時,即可傳遞該模式。
  • UNSPECIFIED 子View想多大就多大,這在某些wrap_content的View中是存在的,內容大小可以超過父容器,只是在屏幕上不能展示,但是通過getMeasuredWidth()獲取的大小是超過父容器的。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章