RatioLayout --> 动态适配图片
package com.heima.googleplay.view; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.widget.FrameLayout; import com.heima.googleplay.R; /** * 创建: 馥溪凝 * 时间: 2016-11-18 下午 12:18. * 描述: 自定义的动态测量宽高比的控件 */ public class RatioLayout extends FrameLayout { public static final int RELATIVE_WIDTH = 0; public static final int RELATIVE_HEIGHT = 1; private float picRatio; private int relative = RELATIVE_WIDTH; public void setPicRatio(float picRatio) { this.picRatio = picRatio; } public void setRelative(int relative) { this.relative = relative; } public RatioLayout(Context context) { this(context, null); } public RatioLayout(Context context, AttributeSet attrs) { super(context, attrs); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatioLayout); picRatio = typedArray.getFloat(R.styleable.RatioLayout_picRatio, 1); relative = typedArray.getInt(R.styleable.RatioLayout_relative, RELATIVE_WIDTH); typedArray.recycle(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // 测量自身的宽高比 int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); if (widthMode == MeasureSpec.EXACTLY && relative == RELATIVE_WIDTH){ int width = MeasureSpec.getSize(widthMeasureSpec); int height = (int) (width / picRatio + .5f); setMeasuredDimension(width, height); //保存测量结果 // 测量孩子的宽高比 int childWidth = width - getPaddingLeft() - getPaddingRight(); int childHeight = height - getPaddingBottom() - getPaddingBottom(); int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY); int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY); measureChildren(childWidthMeasureSpec, childHeightMeasureSpec); }else if (heightMode == MeasureSpec.EXACTLY && relative == RELATIVE_HEIGHT){ int height = MeasureSpec.getSize(heightMeasureSpec); int width = (int) (height * picRatio + .5f); setMeasuredDimension(width, height); //保存测量结果 // 测量孩子的宽高比 int childWidth = width - getPaddingLeft() - getPaddingRight(); int childHeight = height - getPaddingBottom() - getPaddingBottom(); int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY); int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY); measureChildren(childWidthMeasureSpec, childHeightMeasureSpec); }else { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } }
attrs.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="RatioLayout"> <attr name="picRatio" format="float"></attr> <attr name="relative" format="enum"> <enum name="width" value="0"/> <enum name="height" value="1"/> </attr> </declare-styleable> </resources>