效果:
加入wrap_content后一点效果也没有啊,还是显示不全啊,还没加wrap_content一样,- -!
你也可以通过只设置width或者height和layout_aspectRatio这种比例值的方式来让第另一个值自动计算。例如,如果你想要使用16:9的比例,你可以使用:
android:layout_width="300dp"
app:layout_aspectRatio="178%"
这样将会在宽固定为300dp的基础上以16:9(1.78:1)来计算高度。
PercentRelativeLayout的使用都是一样的,这里就不贴了。layout_margintop 百分比
那它是怎么实现的呢?其实就是内部给通过属性换算,把本布局的宽高和百分比去计算每个view的大小和位置。但是还有为什么上面设置的wrap_content无效呢?是我理解错了吗?
带着这两个疑问我们来看下源码:
public class PercentFrameLayout extends FrameLayout {
private final PercentLayoutHelper mHelper = new PercentLayoutHelper(this);
public PercentFrameLayout(Context context) {
super(context);
}
public PercentFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PercentFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
mHelper.adjustChildren(widthMeasureSpec, heightMeasureSpec);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 从名字上就能看出来下面就是处理如果指定百分比过小不足显示内容时,就去使用`wrap_content`的逻辑
if (mHelper.handleMeasuredStateTooSmall()) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
mHelper.restoreOriginalParams();
}
public static class LayoutParams extends FrameLayout.LayoutParams
implements PercentLayoutHelper.PercentLayoutParams {
private PercentLayoutHelper.PercentLayoutInfo mPercentLayoutInfo;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
// PercentLayoutInfo中去解析自定义属性的值
mPercentLayoutInfo = PercentLayoutHelper.getPercentLayoutInfo(c, attrs);
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(int width, int height, int gravity) {
super(width, height, gravity);
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(MarginLayoutParams source) {
super(source);
}
public LayoutParams(FrameLayout.LayoutParams source) {
super((MarginLayoutParams) source);
gravity = source.gravity;
}
public LayoutParams(LayoutParams source) {
this((FrameLayout.LayoutParams) source);
mPercentLayoutInfo = source.mPercentLayoutInfo;
}
@Override
public PercentLayoutHelper.PercentLayoutInfo getPercentLayoutInfo() {
if (mPercentLayoutInfo == null) {
mPercentLayoutInfo = new PercentLayoutHelper.PercentLayoutInfo();
}
return mPercentLayoutInfo;
}
@Override
protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) {
PercentLayoutHelper.fetchWidthAndHeight(this, a, widthAttr, heightAttr);
}
}
}
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-40673-3.html