调用了PercentLayoutInfo.restoreMarginLayoutParams()方法,我们看下它的源码:
/**
* 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}.
*/
public void 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));
}
意思是说,再他们被以百分比为基础的数据更改之后恢复成原始的尺寸和margin。
然后继续看一下restoreLayoutParams():
/**
* 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}.
*/
public void 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;
}
好了到这里也分析完了onLayout的方法,大意就是在onMeasure之前先将原始的宽高和margin都备份一下,然后在onMeasure中根据百分比去设置对应的宽高和margin,等到设置完之后在onLayout方法中再去将这些值恢复到之前备份的起始数据。说实话我没看明白为什么要这样做?
通过上面的代码分析我们知道对布局影响力的优先顺序: app:layout_aspectRatio > app:layout_heightPercent > android:layout_height如果我们同时都设置这三个参数值的话,最终会用app:layout_aspectRatio的值。
遗留问题:
为什么在onLayout方法中去恢复数据,这有什么作用?
看代码在处理如果指定的百分比过小但又指定wrap_content时,会重新根据wrap_content去重新计算的逻辑没有错,但是为什么我在上面测试的时候确没效果?
有知道上面这两个问题的告诉我一下。
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-40673-10.html
是人的基本需要