屏幕适配之百分比方案详解

来源:互联网 发布:软件测试干什么的 编辑:程序博客网 时间:2024/05/20 21:23

最近看到DrawerLayoutsupport v4中提供的类,想到对google提供的这些支持库,自己一点都不熟悉,想着看看Google提供的支持库都有什么内容。结果看着看着在最后忽然看到了Percent Support Library。寻思怎么还百分比呢?仔细一看介绍,我擦,真是太有用了。

Percent Support Library

The Percent package provides APIs to support adding and managing percentage based dimensions in your app.

The Percent Support library adds support for the PercentLayoutHelper.PercentLayoutParams interface and various classes, such as PercentFrameLayout and PercentRelativeLayout.

After you download the Android Support Libraries, this library is located in the /extras/android/support/percent directory. For more information on how to set up your project, follow the instructions in Adding libraries with resources.

The Gradle build script dependency identifier for this library is as follows:
com.android.support:percent:23.3.0

看到了吗? 说提供了PercentFrameLayoutPercentRelativeLayout来支持百分比了。这样不就完美的解决了适配的问题嘛。啥也不说了,立马配置cradle来瞧瞧。

Subclass of FrameLayout that supports percentage based dimensions and margins. You can specify dimension or a margin of child by using attributes with “Percent” suffix.

上代码:

?
1
2
3
<codeclass="language-xml hljs ">
    <imageview android:src="@mipmap/ic_launcher"app:layout_heightpercent="50%"app:layout_marginleftpercent="25%"app:layout_margintoppercent="25%"app:layout_widthpercent="50%">
</imageview></android.support.percent.percentframelayout></code>

效果如下:
image
完美.

支持的属性:

layout_widthPercent layout_heightPercent layout_marginPercent layout_marginLeftPercentlayout_marginTZ喎�"/kf/ware/vc/" target="_blank" class="keylink">vcFBlcmNlbnQ8L2NvZGU+IDxjb2RlPmxheW91dF9tYXJnaW5SaWdodFBlcmNlbnQ8L2NvZGU+IDxjb2RlPmxheW91dF9tYXJnaW5Cb3R0b21QZXJjZW50PC9jb2RlPiA8Y29kZT5sYXlvdXRfbWFyZ2luU3RhcnRQZXJjZW50PC9jb2RlPiA8Y29kZT5sYXlvdXRfbWFyZ2luRW5kUGVyY2VudDwvY29kZT4gPGNvZGU+bGF5b3V0X2FzcGVjdFJhdGlvPC9jb2RlPg0KPGJsb2NrcXVvdGU+DQoJPHA+SXQgaXMgbm90IG5lY2Vzc2FyeSB0byBzcGVjaWZ5IGxheW91dF93aWR0aC9oZWlnaHQgaWYgeW91IHNwZWNpZnkgbGF5b3V0X3dpZHRoUGVyY2VudC4gSG93ZXZlciwgaWYgeW91IHdhbnQgdGhlIHZpZXcgdG8gYmUgYWJsZSB0byB0YWtlIHVwIG1vcmUgc3BhY2UgdGhhbiB3aGF0IHBlcmNlbnRhZ2UgdmFsdWUgcGVybWl0cywgeW91IGNhbiBhZGQgbGF5b3V0X3dpZHRoL2hlaWdodD0mcmRxdW87d3JhcF9jb250ZW50JnJkcXVvOy4gSW4gdGhhdCBjYXNlIGlmIHRoZSBwZXJjZW50YWdlIHNpemUgaXMgdG9vIHNtYWxsIGZvciB0aGUgVmlldyZyc3F1bztzIGNvbnRlbnQsIGl0IHdpbGwgYmUgcmVzaXplZCB1c2luZyB3cmFwX2NvbnRlbnQgcnVsZS48L3A+DQo8L2Jsb2NrcXVvdGU+DQo8cD7I57n71ri2qMHLPGNvZGU+bGF5b3V0X3dpZHRoUGVyY2VudDwvY29kZT6+zbK708PWuLaoPGNvZGU+bGF5b3V0X3dpZHRoL2hlaWdodDwvY29kZT7K9NDUwcuhoyg8Y29kZT5TdHVkaW88L2NvZGU+v8nE3LvhzOHKvrTtzvOjrMno1sO69sLUvs26wymho8i7tvijrMjnufvE48/r0qq4wzxjb2RlPlZpZXc8L2NvZGU+xNy5u9W808OxyMno1sO1xLDZt9axyNa1uPy087XEv9W85Mqxo6zE47/J0tTWuLaoPGNvZGU+bGF5b3V0X3dpZGh0L2hlaWdodD0mbGRxdW87d3JhcF9jb250ZW50JnJkcXVvOzwvY29kZT6ho9Ta1eLW1sfpv/bPwqOsyOe5+8no1sO1xLDZt9axyNa11NrP1Mq+xNrI3cqxzKvQocqxo6y9q7vhyrnTwzxjb2RlPndyYXBfY29udGVudDwvY29kZT61xNa11tjQwrzGy+OhozwvcD4NCjxwPr7NysfV4rj20uLLvDrI57n71ri2qLXEsNm31rHIzKvQocXCz9TKvrK7v6q1xLuwo6zSsr/J0tS4+Mv81ri2qDxjb2RlPndyYXBfY29udGVudDwvY29kZT7K9NDUo6zV4tH5tbHP1Mq+sru/qrXEyrG68r7Nu+HKudPDPGNvZGU+d3JhcF9jb250ZW50PC9jb2RlPrXE1rWhozxiciAvPg0KyOfPwjo8L3A+DQo8cHJlIGNsYXNzPQ=="brush:java;">

效果:
image

加入wrap_content后一点效果也没有啊,还是显示不全啊,还没加wrap_content一样,- -!

你也可以通过只设置width或者heightlayout_aspectRatio这种比例值的方式来让第另一个值自动计算。例如,如果你想要使用16:9的比例,你可以使用:

?
1
2
<codeclass="language-xml hljs ">android:layout_width="300dp"
app:layout_aspectRatio="178%"</code>

这样将会在宽固定为300dp的基础上以16:9(1.78:1)来计算高度。

PercentRelativeLayout的使用都是一样的,这里就不贴了。

那它是怎么实现的呢?其实就是内部给通过属性换算,把本布局的宽高和百分比去计算每个view的大小和位置。但是还有为什么上面设置的wrap_content无效呢?是我理解错了吗?

带着这两个疑问我们来看下源码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<codeclass="language-java hljs ">publicclass PercentFrameLayout extendsFrameLayout {
    privatefinal PercentLayoutHelper mHelper = newPercentLayoutHelper(this);
 
    publicPercentFrameLayout(Context context) {
        super(context);
    }
 
    publicPercentFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
 
    publicPercentFrameLayout(Context context, AttributeSet attrs, intdefStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
 
    @Override
    protectedLayoutParams generateDefaultLayoutParams() {
        returnnew LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    }
 
    @Override
    publicLayoutParams generateLayoutParams(AttributeSet attrs) {
        returnnew LayoutParams(getContext(), attrs);
    }
 
    @Override
    protectedvoid onMeasure(intwidthMeasureSpec, intheightMeasureSpec) {
        mHelper.adjustChildren(widthMeasureSpec, heightMeasureSpec);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 从名字上就能看出来下面就是处理如果指定百分比过小不足显示内容时,就去使用`wrap_content`的逻辑
        if(mHelper.handleMeasuredStateTooSmall()) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
 
    @Override
    protectedvoid onLayout(booleanchanged, intleft, inttop, intright, intbottom) {
        super.onLayout(changed, left, top, right, bottom);
        mHelper.restoreOriginalParams();
    }
 
    publicstatic class LayoutParams extendsFrameLayout.LayoutParams
            implementsPercentLayoutHelper.PercentLayoutParams {
 
        privatePercentLayoutHelper.PercentLayoutInfo mPercentLayoutInfo;
 
        publicLayoutParams(Context c, AttributeSet attrs) {
            super(c, attrs);
            // PercentLayoutInfo中去解析自定义属性的值
            mPercentLayoutInfo = PercentLayoutHelper.getPercentLayoutInfo(c, attrs);
        }
 
        publicLayoutParams(intwidth, intheight) {
            super(width, height);
        }
 
        publicLayoutParams(intwidth, intheight, intgravity) {
            super(width, height, gravity);
        }
 
        publicLayoutParams(ViewGroup.LayoutParams source) {
            super(source);
        }
 
        publicLayoutParams(MarginLayoutParams source) {
            super(source);
        }
 
        publicLayoutParams(FrameLayout.LayoutParams source) {
            super((MarginLayoutParams) source);
            gravity = source.gravity;
        }
 
        publicLayoutParams(LayoutParams source) {
            this((FrameLayout.LayoutParams) source);
            mPercentLayoutInfo = source.mPercentLayoutInfo;
        }
 
        @Override
        publicPercentLayoutHelper.PercentLayoutInfo getPercentLayoutInfo() {
            if(mPercentLayoutInfo == null) {
                mPercentLayoutInfo = newPercentLayoutHelper.PercentLayoutInfo();
            }
 
            returnmPercentLayoutInfo;
        }
 
        @Override
        protectedvoid setBaseAttributes(TypedArray a, intwidthAttr, intheightAttr) {
            PercentLayoutHelper.fetchWidthAndHeight(this, a, widthAttr, heightAttr);
        }
    }
}</code>

源码不长,主要是三个部分:

重写onMeasure,根据百分比转换成对应的尺寸 重写onLayout 自定义LayoutParams,在FrameLayout.LayoutParams的基础上多实现了一个接口。包含了PercentLayoutHelper.PercentLayoutInfo属性,而文档中对PercentLayoutInfo的介绍是Container for information about percentage dimensions and margins. It acts as an extension for LayoutParams.

我们也先一步步的来分析,首先看下mHelper.adjustChildren(widthMeasureSpec, heightMeasureSpec);:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<codeclass="language-java hljs ">/**
     * Iterates over children and changes their width and height to one calculated from percentage
     * values.
     * @param widthMeasureSpec Width MeasureSpec of the parent ViewGroup.
     * @param heightMeasureSpec Height MeasureSpec of the parent ViewGroup.
     */
publicvoid adjustChildren(intwidthMeasureSpec, intheightMeasureSpec) {
        if(Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG,"adjustChildren: " + mHost + " widthMeasureSpec: "
                    + View.MeasureSpec.toString(widthMeasureSpec) + " heightMeasureSpec: "
                    + View.MeasureSpec.toString(heightMeasureSpec));
        }
 
        intwidthHint = View.MeasureSpec.getSize(widthMeasureSpec);
        intheightHint = View.MeasureSpec.getSize(heightMeasureSpec);
        // mHost是由构造函数传递过来的,就是PercentFrameLayout自身。
        for(inti = 0, N = mHost.getChildCount(); i < N; i++) {
            View view = mHost.getChildAt(i);
            ViewGroup.LayoutParams params = view.getLayoutParams();
            if(Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG,"should adjust " + view + " " + params);
            }
            if(params instanceofPercentLayoutParams) {
                // 通过PercentLayoutParams. getPercentLayoutInfo()方法得到PercentLayoutInfo,至于PercentLayoutInfo类在上面也说过了。
                PercentLayoutInfo info =
                        ((PercentLayoutParams) params).getPercentLayoutInfo();
                if(Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG,"using " + info);
                }
                if(info != null) {
                    if(params instanceofViewGroup.MarginLayoutParams) {
                        // PercentFrameLayout.LayoutParams继承自FrameLayout.LayoutParams,而FrameLayout.LayoutParams又继承自ViewGroup.MarginLayoutParams
                        info.fillMarginLayoutParams(view, (ViewGroup.MarginLayoutParams) params,
                                widthHint, heightHint);
                    }else{
                        info.fillLayoutParams(params, widthHint, heightHint);
                    }
                }
            }
        }
    }</code>

所以上面代码的意思就是通过对每个子View调用getLayoutParams方法,然后从该LayoutParams中获取到它的PercentLayoutInfo属性,然后再调用PercentLayoutInfo.fillMarginLayoutParams()方法。

那我们继续看一下PercentLayoutInfo.fillMarginLayoutParams()方法的实现,该方法是根据百分比去设置尺寸和margin:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<codeclass="language-java hljs ">/**
         * Fills {@code ViewGroup.MarginLayoutParams} dimensions and margins based on percentage
         * values.
         */
        publicvoid fillMarginLayoutParams(View view, ViewGroup.MarginLayoutParams params,
                intwidthHint, intheightHint) {
            // 根据百分比值设置View的尺寸
            fillLayoutParams(params, widthHint, heightHint);
 
            // 从注释中就能知道,fillLayoutParams是计算尺寸,那下面这部分就是处理margin了
            // mPreservedParams来记录原始的margin值
            // Preserve the original margins, so we can restore them after the measure step.
            mPreservedParams.leftMargin = params.leftMargin;
            mPreservedParams.topMargin = params.topMargin;
            mPreservedParams.rightMargin = params.rightMargin;
            mPreservedParams.bottomMargin = params.bottomMargin;
            MarginLayoutParamsCompat.setMarginStart(mPreservedParams,
                    MarginLayoutParamsCompat.getMarginStart(params));
            MarginLayoutParamsCompat.setMarginEnd(mPreservedParams,
                    MarginLayoutParamsCompat.getMarginEnd(params));
 
            if(leftMarginPercent >= 0) {
                params.leftMargin = (int) (widthHint * leftMarginPercent);
            }
            if(topMarginPercent >= 0) {
                params.topMargin = (int) (heightHint * topMarginPercent);
            }
            if(rightMarginPercent >= 0) {
                params.rightMargin = (int) (widthHint * rightMarginPercent);
            }
            if(bottomMarginPercent >= 0) {
                params.bottomMargin = (int) (heightHint * bottomMarginPercent);
            }
            booleanshouldResolveLayoutDirection = false;
            if(startMarginPercent >= 0) {
                MarginLayoutParamsCompat.setMarginStart(params,
                        (int) (widthHint * startMarginPercent));
                shouldResolveLayoutDirection = true;
            }
            if(endMarginPercent >= 0) {
                MarginLayoutParamsCompat.setMarginEnd(params,
                        (int) (widthHint * endMarginPercent));
                shouldResolveLayoutDirection = true;
            }
            if(shouldResolveLayoutDirection && (view != null)) {
                // Force the resolve pass so that start / end margins are propagated to the
                // matching left / right fields
                MarginLayoutParamsCompat.resolveLayoutDirection(params,
                        ViewCompat.getLayoutDirection(view));
            }
            if(Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG,"after fillMarginLayoutParams: (" + params.width + ", " + params.height
                        +")");
            }
        }</code>

再看一下PercentLayoutInfo.fillLayoutParams()的实现,该方法是通过百分比设置View的尺寸:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<codeclass="language-java hljs ">       /**
         * Fills {@code ViewGroup.LayoutParams} dimensions based on percentage values.
         */
        publicvoid fillLayoutParams(ViewGroup.LayoutParams params, intwidthHint,
                intheightHint) {
            // mPreservedParams来记录原始的宽高值
            // Preserve the original layout params, so we can restore them after the measure step.
            mPreservedParams.width = params.width;
            mPreservedParams.height = params.height;
 
            // We assume that width/height set to 0 means that value was unset. This might not
            // necessarily be true, as the user might explicitly set it to 0. However, we use this
            // information only for the aspect ratio. If the user set the aspect ratio attribute,
            // it means they accept or soon discover that it will be disregarded.
            finalboolean widthNotSet =
                    (mPreservedParams.mIsWidthComputedFromAspectRatio
                            || mPreservedParams.width == 0) && (widthPercent < 0);
            finalboolean heightNotSet =
                    (mPreservedParams.mIsHeightComputedFromAspectRatio
                            || mPreservedParams.height == 0) && (heightPercent < 0);
 
            // 如果指定了百分比属性,就用宽高值和百分比去算出具体的宽高
            if(widthPercent >= 0) {
                params.width = (int) (widthHint * widthPercent);
            }
 
            if(heightPercent >= 0) {
                params.height = (int) (heightHint * heightPercent);
            }
            // 如果指定了宽高的比例值,就用比例值去算出宽高,从这里能看出`aspectRatio`的优先级比百分比要高。他可以覆盖百分比之前设置的值。
            if(aspectRatio >= 0) {
                if(widthNotSet) {
                    params.width = (int) (params.height * aspectRatio);
                    // Keep track that we've filled the width based on the height and aspect ratio.
                    mPreservedParams.mIsWidthComputedFromAspectRatio = true;
                }
                if(heightNotSet) {
                    params.height = (int) (params.width / aspectRatio);
                    // Keep track that we've filled the height based on the width and aspect ratio.
                    mPreservedParams.mIsHeightComputedFromAspectRatio = true;
                }
            }
 
            if(Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG,"after fillLayoutParams: (" + params.width + ", " + params.height + ")");
            }
        }
</code>

到这里onMeasure中通过百分比值设置宽高以及margin的部分就看完了,那我们接着看一下关于百分比值过小时对wrap_content的处理:

?
1
2
3
<codeclass="language-java hljs ">if(mHelper.handleMeasuredStateTooSmall()) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}</code>

看一下PercentLayoutHelper.handleMeasuredStateTooSmall()方法的实现:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<codeclass="language-java hljs ">/**
     * Iterates over children and checks if any of them would like to get more space than it
     * received through the percentage dimension.
     *
     * If you are building a layout that supports percentage dimensions you are encouraged to take
     * advantage of this method. The developer should be able to specify that a child should be
     * remeasured by adding normal dimension attribute with {@code wrap_content} value. For example
     * he might specify child's attributes as {@code app:layout_widthPercent="60%p"} and
     * {@code android:layout_width="wrap_content"}. In this case if the child receives too little
     * space, it will be remeasured with width set to {@code WRAP_CONTENT}.
     *
     * @return True if the measure phase needs to be rerun because one of the children would like
     * to receive more space.
     */
    publicboolean handleMeasuredStateTooSmall() {
        booleanneedsSecondMeasure = false;
        for(inti = 0, N = mHost.getChildCount(); i < N; i++) {
            View view = mHost.getChildAt(i);
            ViewGroup.LayoutParams params = view.getLayoutParams();
            if(Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG,"should handle measured state too small " + view + " " + params);
            }
            if(params instanceofPercentLayoutParams) {
                PercentLayoutInfo info =
                        ((PercentLayoutParams) params).getPercentLayoutInfo();
                if(info != null) {
                    // shouldHandleMeasuredWidthTooSmall方法来进行判断
                    if(shouldHandleMeasuredWidthTooSmall(view, info)) {
                        needsSecondMeasure = true;
                        params.width = ViewGroup.LayoutParams.WRAP_CONTENT;
                    }
                    if(shouldHandleMeasuredHeightTooSmall(view, info)) {
                        needsSecondMeasure = true;
                        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                    }
                }
            }
        }
        if(Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG,"should trigger second measure pass: " + needsSecondMeasure);
        }
        returnneedsSecondMeasure;
    }</code>

那继续看一下shouldHandleMeasuredWidthTooSmall()方法:

?
1
2
3
4
5
<codeclass="language-java hljs ">privatestatic boolean shouldHandleMeasuredWidthTooSmall(View view, PercentLayoutInfo info) {
        intstate = ViewCompat.getMeasuredWidthAndState(view) & ViewCompat.MEASURED_STATE_MASK;
        returnstate == ViewCompat.MEASURED_STATE_TOO_SMALL && info.widthPercent >= 0&&
                info.mPreservedParams.width == ViewGroup.LayoutParams.WRAP_CONTENT;
    }</code>

继续看ViewCompat.getMeasuredWidthAndState()的源码:

?
1
2
3
<codeclass="language-java hljs ">publicstatic int getMeasuredWidthAndState(View view) {
        returnIMPL.getMeasuredWidthAndState(view);
    }</code>

继续往下看,这个IMPL是什么呢?

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<codeclass="language-java hljs ">staticfinal ViewCompatImpl IMPL;
    static{
        finalint version = android.os.Build.VERSION.SDK_INT;
        if(version >= 23) {
            IMPL = newMarshmallowViewCompatImpl();
        }elseif (version >= 21) {
            IMPL = newLollipopViewCompatImpl();
        }elseif (version >= 19) {
            IMPL = newKitKatViewCompatImpl();
        }elseif (version >= 17) {
            IMPL = newJbMr1ViewCompatImpl();
        }elseif (version >= 16) {
            IMPL = newJBViewCompatImpl();
        }elseif (version >= 15) {
            IMPL = newICSMr1ViewCompatImpl();
        }elseif (version >= 14) {
            IMPL = newICSViewCompatImpl();
        }elseif (version >= 11) {
            IMPL = newHCViewCompatImpl();
        }elseif (version >= 9) {
            IMPL = newGBViewCompatImpl();
        }elseif (version >= 7) {
            IMPL = newEclairMr1ViewCompatImpl();
        }else{
            IMPL = newBaseViewCompatImpl();
        }
    }</code>

继续看,IMPL.getMeasuredWidthAndState(),方法其实最终就是使用的BaseViewCompatImpl.getMeasuredWidthAndState()方法,接着看它的的源码:

?
1
2
3
4
<codeclass="language-java hljs ">@Override
        publicint getMeasuredWidthAndState(View view) {
            returnview.getMeasuredWidth();
        }</code>

最后就是调用了getMeasuredWidth()方法。 没毛病- -!

onMeasure的到这里就分析完了。
那接着来看一下onLayout方法,onLayout方法直接调用了PercentLayoutHelper.restoreOriginalParams,:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<codeclass="language-java hljs ">/**
     * Iterates over children and restores their original dimensions that were changed for
     * percentage values. Calling this method only makes sense if you previously called
     * {@link PercentLayoutHelper#adjustChildren(int, int)}.
     */
    publicvoid restoreOriginalParams() {
        for(inti = 0, N = mHost.getChildCount(); i < N; i++) {
            View view = mHost.getChildAt(i);
            ViewGroup.LayoutParams params = view.getLayoutParams();
            if(Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG,"should restore " + view + " " + params);
            }
            if(params instanceofPercentLayoutParams) {
                PercentLayoutInfo info =
                        ((PercentLayoutParams) params).getPercentLayoutInfo();
                if(Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG,"using " + info);
                }
                if(info != null) {
                    if(params instanceofViewGroup.MarginLayoutParams) {
                        info.restoreMarginLayoutParams((ViewGroup.MarginLayoutParams) params);
                    }else{
                        info.restoreLayoutParams(params);
                    }
                }
            }
        }
    }</code>

调用了PercentLayoutInfo.restoreMarginLayoutParams()方法,我们看下它的源码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<codeclass="language-java hljs ">/**
         * Restores original dimensions and margins after they were changed for percentage based
         * values. Calling this method only makes sense if you previously called
         * {@link PercentLayoutHelper.PercentLayoutInfo#fillMarginLayoutParams}.
         */
        publicvoid restoreMarginLayoutParams(ViewGroup.MarginLayoutParams params) {
            restoreLayoutParams(params);
            // mPreservedParams的值在之前ad
            params.leftMargin = mPreservedParams.leftMargin;
            params.topMargin = mPreservedParams.topMargin;
            params.rightMargin = mPreservedParams.rightMargin;
            params.bottomMargin = mPreservedParams.bottomMargin;
            MarginLayoutParamsCompat.setMarginStart(params,
                    MarginLayoutParamsCompat.getMarginStart(mPreservedParams));
            MarginLayoutParamsCompat.setMarginEnd(params,
                    MarginLayoutParamsCompat.getMarginEnd(mPreservedParams));
        }
</code>

意思是说,再他们被以百分比为基础的数据更改之后恢复成原始的尺寸和margin。
然后继续看一下restoreLayoutParams():

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<codeclass="language-java hljs ">/**
         * Restores original dimensions after they were changed for percentage based values. Calling
         * this method only makes sense if you previously called
         * {@link PercentLayoutHelper.PercentLayoutInfo#fillLayoutParams}.
         */
        publicvoid restoreLayoutParams(ViewGroup.LayoutParams params) {
            if(!mPreservedParams.mIsWidthComputedFromAspectRatio) {
                // Only restore the width if we didn't compute it based on the height and
                // aspect ratio in the fill pass.
                params.width = mPreservedParams.width;
            }
            if(!mPreservedParams.mIsHeightComputedFromAspectRatio) {
                // Only restore the height if we didn't compute it based on the width and
                // aspect ratio in the fill pass.
                params.height = mPreservedParams.height;
            }
 
            // Reset the tracking flags.
            mPreservedParams.mIsWidthComputedFromAspectRatio = false;
            mPreservedParams.mIsHeightComputedFromAspectRatio = false;
        }</code>

好了到这里也分析完了onLayout的方法,大意就是在onMeasure之前先将原始的宽高和margin都备份一下,然后在onMeasure中根据百分比去设置对应的宽高和margin,等到设置完之后在onLayout方法中再去将这些值恢复到之前备份的起始数据。说实话我没看明白为什么要这样做?

通过上面的代码分析我们知道对布局影响力的优先顺序: app:layout_aspectRatio > app:layout_heightPercent > android:layout_height如果我们同时都设置这三个参数值的话,最终会用app:layout_aspectRatio的值。

遗留问题:

为什么在onLayout方法中去恢复数据,这有什么作用? 看代码在处理如果指定的百分比过小但又指定wrap_content时,会重新根据wrap_content去重新计算的逻辑没有错,但是为什么我在上面测试的时候确没效果?

有知道上面这两个问题的告诉我一下。


更多内容请关注Github

0 0
原创粉丝点击