Android自定义View——可以设置最大宽高的FrameLayout

简介: Android自定义View——可以设置最大宽高的FrameLayout

Android开发中,我们经常需要自定义View来满足特定的需求。其中,修改FrameLayout的高宽通常是一个常见的需求。本文将介绍如何自定义FrameLayout并修改其高宽。

FrameLayout简介

FrameLayout是Android中常用的布局容器之一,它可以包含多个子View,并按照它们在布局中的顺序进行叠加。每个子View可能会占据不同的位置和大小,但它们都会显示在FrameLayout的左上角。

自定义FrameLayout

要修改FrameLayout的高宽,我们可以自定义一个继承自FrameLayout的类,并在其中重写onMeasure方法。onMeasure方法用于测量子View的大小并设置布局容器的大小。

话不多说,直接上代码。

MaxLayout.java

import android.util.DisplayMetrics;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.WindowManager;
 
 
/**
 *
 * 可以设置最大宽高的FrameLayout
 * 默认优先比例设置
 * 不支持参数小于零
 *
 */
public class MaxLayout extends FrameLayout {
    private float mMaxHeightRatio = -1f;// 优先级高
    private float mMaxHeight = -1f;// 优先级低
    private float mMaxWidthRatio = -1f;// 优先级高
    private float mMaxWidth = -1f;// 优先级低
    private int parentWidth;
    private int parentHeight;
    private boolean firstHeightRatio = true;//高默认优先比例设置
    private boolean firstWidthRatio = true;//宽默认优先比例设置
 
    public MaxLayout(Context context) {
        super(context);
    }
 
    public MaxLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAttrs(context, attrs);
    }
 
    public MaxLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initAttrs(context, attrs);
    }
 
    private void initAttrs(Context context, AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.MaxLayout);
        if(a!=null){
            firstHeightRatio = a.getBoolean(R.styleable.MaxLayout_first_ratio_height,true);
            firstWidthRatio = a.getBoolean(R.styleable.MaxLayout_first_ratio_width,true);
            mMaxHeightRatio = a.getFloat(R.styleable.MaxLayout_max_height_ratio, -1f);
            mMaxHeight = a.getDimension(R.styleable.MaxLayout_max_height, -1f);
            mMaxWidthRatio = a.getFloat(R.styleable.MaxLayout_max_width_ratio, -1f);
            mMaxWidth = a.getDimension(R.styleable.MaxLayout_max_width, -1f);
            a.recycle();
        }
    }
 
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        initParentWH();
        initWH();
 
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
 
        int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize <= mMaxHeight ? heightSize : (int) mMaxHeight, heightMode);
 
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int maxWidthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize <= mMaxWidth ? widthSize : (int) mMaxWidth, widthMode);
 
        super.onMeasure(maxWidthMeasureSpec, maxHeightMeasureSpec);
    }
 
    /**
     * 计算需要设置的宽高
     */
    private void initWH() {
        if((firstHeightRatio && mMaxHeightRatio > 0)
                || (!firstHeightRatio && mMaxHeight < 0)){
            mMaxHeight = mMaxHeightRatio * parentHeight;
        }
        if((firstWidthRatio && mMaxWidthRatio > 0)
                || (!firstWidthRatio && mMaxWidth < 0)){
            mMaxWidth = mMaxWidthRatio * parentWidth;
        }
    }
 
    /**
     * 获取父控件的宽高
     */
    private void initParentWH() {
        ViewGroup parent = (ViewGroup) getParent();
        if(null != parent){
            parentWidth = parent.getWidth();
            parentHeight = parent.getHeight();
        }else {
            WindowManager wm = (WindowManager) getContext()
                    .getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics dm = new DisplayMetrics();
            if (wm != null) {
                wm.getDefaultDisplay().getMetrics(dm);
                parentWidth = dm.widthPixels;
                parentHeight = dm.heightPixels;
            }
        }
    }
}

attrs.xml

    <declare-styleable name="MaxLayout">
        <attr name="max_height_ratio" format="float"/>
        <attr name="max_height" format="dimension"/>
        <attr name="max_width_ratio" format="float"/>
        <attr name="max_width" format="dimension"/>
        <attr name="first_ratio_height" format="boolean"/>
        <attr name="first_ratio_width" format="boolean"/>
    </declare-styleable>

在实际项目开发中,如果在Scrollview(也限定了宽高)中嵌套了限定宽高的Framelayout,可能会出现Framelayout里面的子view最底部的显示不出来的问题,那么就需要对上面的代码进行一定的改动。

思路:

  1. Framelayout 的高度应该是所有子view的高度的和;
  2. 由于Framelayout动态添加子view的时候如果不指定坐标的话或叠在一起,所以一般都会指定坐标;
  3. 对Framelayout里面的子view进行遍历,获取Y坐标最大的子view和该view的高度(也要考虑他的Margin值);
  4. Framelayout 的高度实际上就是最大Y坐标的子view的高度+最大Y坐标的值。

同时也就解决了FrameLayout添加子view显示不全或者显示个数不完整的问题。

/**
 * 可以设置最大宽高的FrameLayout
 */
public class MaxFrameLayout extends FrameLayout {
 
    private static final String TAG = "MaxFrameLayout";
 
    private int mMaxHeight = 0;
    private int mMaxWidth = 0;
 
    public MaxFrameLayout(Context context) {
        super(context);
    }
 
    public MaxFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
 
    public MaxFrameLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
 
    public MaxFrameLayout(Context context, int maxWidth, int maxHeight) {
        super(context);
        mMaxWidth = maxWidth;
        mMaxHeight = maxHeight;
    }
 
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
 
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
 
        int realHeight = Math.max(getParentHeight(getChildCount()), mMaxHeight);
        Log.e(TAG, "onMeasure  heightSize " + heightSize + " realHeight " + realHeight + "  mMaxHeight " + mMaxHeight);
 
        int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.max(heightSize, realHeight), heightMode);
 
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int maxWidthMeasureSpec = MeasureSpec.makeMeasureSpec(Math.min(widthSize, mMaxWidth), widthMode);
 
        super.onMeasure(maxWidthMeasureSpec, maxHeightMeasureSpec);
    }
 
    /**
     * 根据子view的坐标确定getParent的高度
     * @param size
     * @return
     */
    public int getParentHeight(int size) {
        int height = 0;
        int maxIndex = 0;
        int maxY = 0;//获取最底部view的Y坐标
        for (int i = 0; i < size; i++) {
            View child = getChildAt(i);
            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
            int y = (int) child.getY();
            maxY = Math.max(y, maxY);
            if(maxY == y) {
                maxIndex = i;
                final int hPadding = lp.topMargin + lp.bottomMargin;
                height = maxY + lp.height + hPadding;
            }
            Log.d(TAG, "maxIndex " + maxIndex + " maxY " + maxY + " height " + height);
        }
        return height;
    }
 
 
}

其他实现方式。

一、自定义FrameLayout

public class CustomFrameLayout extends FrameLayout {
 
    public CustomFrameLayout(Context context) {
        super(context);
    }
 
    public CustomFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
 
    public CustomFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
 
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
 
        int width = 0;
        int height = 0;
 
        // 计算子View的宽度和高度
 
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            width = Math.max(width, child.getMeasuredWidth());
            height = Math.max(height, child.getMeasuredHeight());
        }
 
        // 根据测量模式设置最终的宽度和高度
 
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthSize;
        } else if (widthMode == MeasureSpec.AT_MOST) {
            width = Math.min(width, widthSize);
        }
 
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightSize;
        } else if (heightMode == MeasureSpec.AT_MOST) {
            height = Math.min(height, heightSize);
        }
 
        // 设置最终的宽度和高度
 
        setMeasuredDimension(width, height);
    }
}

使用自定义FrameLayout

使用自定义的FrameLayout和使用普通的FrameLayout没有太大的区别,只需要在布局文件中使用我们定义的CustomFrameLayout即可。

<com.example.CustomFrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <!-- 子View的布局 -->
 
</com.example.CustomFrameLayout>

二、自定义FrameLayout

GitHub - gdutxiaoxu/MaxLayout

MaxLayout.java

package com.xj.maxlayout;
 
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.IntDef;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.FrameLayout;
 
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
 
/**
 * This layout could set maxWidth,maxHeight,ratio
 * <p>
 * Created by jun xu on 19-2-1.
 */
public class MaxLayout extends FrameLayout {
 
    private static final String TAG = "MaxLayout";
    public static final float DEF_VALUE = -1f;
 
    public static final int W_H = 1;
    public static final int H_W = 2;
    public static final int STANDRAD = 0;
 
    private Context mContext;
 
    private float mMaxHeight = -1f;
    private float mMaxWidth = -1f;
 
    private @RatioStandrad
    int mRatioStandrad;
    private float mRatio;
 
    @IntDef({STANDRAD, W_H, H_W})
    @Retention(RetentionPolicy.SOURCE)
    public @interface RatioStandrad {
    }
 
    public MaxLayout(Context context) {
        this(context, null, 0);
    }
 
    public MaxLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
 
    public MaxLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
        initAttrs(attrs);
    }
 
    private void initAttrs(AttributeSet attrs) {
        TypedArray ta = mContext.obtainStyledAttributes(attrs, R.styleable.MaxLayout);
        mMaxHeight = ta.getDimension(R.styleable.MaxLayout_ml_maxheight, DEF_VALUE);
        mMaxWidth = ta.getDimension(R.styleable.MaxLayout_ml_maxWidth, DEF_VALUE);
        mRatioStandrad = ta.getInt(R.styleable.MaxLayout_ml_ratio_standard, STANDRAD);
        mRatio = ta.getFloat(R.styleable.MaxLayout_ml_ratio, 0);
 
        ta.recycle();
    }
 
    public void setMaxHeight(float maxHeight) {
        mMaxHeight = maxHeight;
    }
 
    public void setMaxWidth(float maxWidth) {
        mMaxWidth = maxWidth;
    }
 
    public void setRatioStandrad(int ratioStandrad) {
        mRatioStandrad = ratioStandrad;
    }
 
    /**
     * only mRatioStandrad is {@link #W_H, #H_W},this is effective
     *
     * @param ratio
     */
    public void setRatio(float ratio) {
        mRatio = ratio;
    }
 
    public float getMaxHeight() {
        return mMaxHeight;
    }
 
    public float getMaxWidth() {
        return mMaxWidth;
    }
 
    public int getRatioStandrad() {
        return mRatioStandrad;
    }
 
    public float getRatio() {
        return mRatio;
    }
 
    public void clearMaxWidthFlag() {
        mMaxWidth = -1f;
    }
 
    public void clearMaxHeightFlag() {
        mMaxHeight = -1f;
    }
 
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // 是否设置了比例
        boolean setRatio = isSetRatio();
        // 没有设置最大宽度,高度,宽高比例,不需要调整,直接返回
        if (mMaxWidth <= DEF_VALUE && mMaxHeight <= DEF_VALUE && !setRatio) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            return;
        }
 
        // 拿到原来宽度,高度的 mode 和 size
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
 
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
 
        Log.d(TAG, "origin onMeasure: widthSize =" + widthSize + "heightSize = " + heightSize);
 
        if (mRatioStandrad == W_H) { // 当模式已宽度为基准
            widthSize = getWidth(widthSize);
 
            if (mRatio >= 0) {
                heightSize = (int) (widthSize * mRatio);
 
            }
 
            heightSize = getHeight(heightSize);
            int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY);
            int maxWidthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, widthMode);
            super.onMeasure(maxWidthMeasureSpec, maxHeightMeasureSpec);
 
        } else if (mRatioStandrad == H_W) { // 当模式已高度为基准
            heightSize = getHeight(heightSize);
 
            if (mRatio >= 0) {
                widthSize = (int) (heightSize * mRatio);
            }
 
            widthSize = getWidth(widthSize);
 
            int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, heightMode);
            int maxWidthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
            super.onMeasure(maxWidthMeasureSpec, maxHeightMeasureSpec);
 
        } else { // 当没有设定比例的时候
            widthSize = getWidth(widthSize);
            heightSize = getHeight(heightSize);
            int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, heightMode);
            int maxWidthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, widthMode);
            super.onMeasure(maxWidthMeasureSpec, maxHeightMeasureSpec);
 
        }
 
        Log.d(TAG, "adjust onMeasure: widthSize =" + widthSize + "heightSize = " + heightSize);
 
    }
 
    // 对宽度进行调整,是否超出最大宽度,超出取最大宽度,没超出,取原来的值
    private int getWidth(int widthSize) {
        if (mMaxWidth <= DEF_VALUE) {
            return widthSize;
        }
 
        return widthSize <= mMaxWidth ? widthSize : (int) mMaxWidth;
    }
 
    // 对高度进行调整,是否超出最大高度,超出取最大高度,没超出,取原来的值
    private int getHeight(int heightSize) {
        if (mMaxHeight <= DEF_VALUE) {
            return heightSize;
        }
        return heightSize <= mMaxHeight ? heightSize : (int) mMaxHeight;
    }
 
    private boolean isSetRatio() {
        return mRatio > 0f && (mRatioStandrad == W_H || mRatioStandrad == H_W);
    }
 
}

使用说明

常用的自定义属性

<declare-styleable> 
   <attr name="ml_maxWidth" format="dimension" />
    <attr name="ml_maxheight" format="dimension" />
    <attr name="ml_ratio" format="float" />
    <attr name="ml_ratio_standard">
        <enum name="w_h" value="1" />
        <enum name="h_w" value="2" />
    </attr>
</declare-styleable>

指定最大宽度,高度

指定最大宽度,最大高度,我们值需要使用 ml_maxWidth,ml_maxheight 属性即可,当然我们也可以同时指定最大宽度和最大高度。如下

<com.xj.maxlayout.MaxLayout
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_marginTop="15dp"
    android:background="@android:color/holo_blue_light"
    app:ml_maxWidth="200dp">
 
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="10dp"
        android:text="指定最大宽度,指定最大宽度,指定最大宽度" />
 
</com.xj.maxlayout.MaxLayout>
 
<com.xj.maxlayout.MaxLayout
    android:layout_width="200dp"
    android:layout_height="match_parent"
    android:layout_marginTop="15dp"
    android:background="@android:color/holo_blue_light"
    app:ml_maxheight="200dp">
 
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:gravity="center"
        android:padding="10dp"
        android:text="指定最大高度" />
 
</com.xj.maxlayout.MaxLayout>
 
<com.xj.maxlayout.MaxLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_marginTop="15dp"
    android:background="@android:color/holo_blue_light"
    app:ml_maxWidth="200dp"
    app:ml_maxheight="150dp">
 
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="10dp"
        android:text="同时指定最大宽度和最大高度" />
 
</com.xj.maxlayout.MaxLayout>

指定宽高比

指定宽高比,我们需要设置两个属性,ml_ratio_standard 和 ml_ratio。ml_ratio_standard 有两个值,w_h 代表已宽度为基准,h_w 代表已高度为基准。

<com.xj.maxlayout.MaxLayout
    android:id="@+id/ml_1"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:background="@color/colorAccent"
    app:ml_ratio="2.0"
    app:ml_ratio_standard="w_h">
 
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@mipmap/jsy03" />
 
 
</com.xj.maxlayout.MaxLayout>

比如,我们要指定宽度是高度的某个比例的时候,如,宽度是高度的 0.8,可以这样写

<com.xj.maxlayout.MaxLayout
    android:id="@+id/ml_2"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:layout_marginLeft="20dp"
    android:layout_toRightOf="@id/ml_1"
    android:background="@android:color/holo_blue_light"
    app:ml_ratio="0.8"
    app:ml_ratio_standard="h_w">
 
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@mipmap/jsy04" />
 
</com.xj.maxlayout.MaxLayout>
 

当然,也可以同时指定比例和最大宽度,高度。

<com.xj.maxlayout.MaxLayout
    android:id="@+id/ml_03"
    android:layout_width="match_parent"
    android:layout_height="220dp"
    android:layout_below="@id/ml_1"
    android:layout_marginTop="15dp"
    android:background="@android:color/holo_blue_light"
    app:ml_maxWidth="150dp">
 
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@mipmap/jsy05" />
 
</com.xj.maxlayout.MaxLayout>
 

原理介绍

原理其实很简单,对自定义 View 有基本了解的人都知道,View 的宽度和高度,是在 onMeasure 方法中进行测量的,他们的大小受 MeasureSpec 的影响。既然如此,那么我们在继承 FrameLayout,重写它的 onMeasure 方法。在 onMeasure 方法中根据我们指定的最大宽度,高度和比例对 MeasureSpec 进行调整即可。

思路大概如下

  • 没有设置最大宽度,高度,宽高比例,不需要调整,直接返回
  • 先拿到原来的 mode 和 size,暂存起来
  • 根据宽高的比例进行相应的调整
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // 是否设置了比例
    boolean setRatio = isSetRatio();
    // 没有设置最大宽度,高度,宽高比例,不需要调整,直接返回
    if (mMaxWidth <= DEF_VALUE && mMaxHeight <= DEF_VALUE && !setRatio) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        return;
    }
 
    // 拿到原来宽度,高度的 mode 和 size
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);
 
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
 
    Log.d(TAG, "origin onMeasure: widthSize =" + widthSize + "heightSize = " + heightSize);
 
    if (mRatioStandrad == W_H) { // 当模式已宽度为基准
        widthSize = getWidth(widthSize);
 
        if (mRatio >= 0) {
            heightSize = (int) (widthSize * mRatio);
        }
 
        heightSize = getHeight(heightSize);
        int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY);
        int maxWidthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, widthMode);
        super.onMeasure(maxWidthMeasureSpec, maxHeightMeasureSpec);
 
    } else if (mRatioStandrad == H_W) { // 当模式已高度为基准
        heightSize = getHeight(heightSize);
 
        if (mRatio >= 0) {
            widthSize = (int) (heightSize * mRatio);
        }
 
        widthSize = getWidth(widthSize);
 
        int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, heightMode);
        int maxWidthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
        super.onMeasure(maxWidthMeasureSpec, maxHeightMeasureSpec);
 
    } else { // 当没有设定比例的时候
        widthSize = getWidth(widthSize);
        heightSize = getHeight(heightSize);
        int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, heightMode);
        int maxWidthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, widthMode);
        super.onMeasure(maxWidthMeasureSpec, maxHeightMeasureSpec);
 
    }
 
    Log.d(TAG, "adjust onMeasure: widthSize =" + widthSize + "heightSize = " + heightSize);
    
}

我们来看一下,有三种模式:

  1. 当模式已宽度为基准的时候,我们首先对宽度进行调整,是否超出最大宽度,超出取最大宽度,没超出,取原来的值。接着,高度按照 mRatio 进行调整,接着判断高度是否超出最大高度,超出取最大高度,没超出,取原来的值。最后,根据相应的 size,mode 生成相应的 MeasureSpec
  2. 当模式已高度为基准的时候,我们首先对高度进行调整,是否超出最大高度,超出取最大高度,没超出,取原来的值。接着,宽度按照 mRatio 进行调整,接着判断宽度是否超出最大宽度,超出取最大宽度,没超出,取原来的值。最后,根据相应的 size,mode 生成相应的 MeasureSpec
  3. 当模式是默认,没有指定宽度或者高度作为基准的时候,直接判断宽高度是否超出最大的宽高度,制定相应的 MeasureSpec 即可。

三、自定义FrameLayout

完整项目示例Git仓库

CustomFrameLayout: The CustomMaxSizeFrameLayout extends FrameLayout can make its child have the custom attribute maxWidth and maxHeight.

package com.example.jokerlee.custommaxsizeframelayout;
 
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewDebug;
import android.view.ViewGroup;
import android.widget.FrameLayout;
 
/**
 * Created by jokerlee on 16-3-14.
 */
public class CustomFramlayout extends FrameLayout {
 
    private static final String TAG = "CustomFramlayout";
    private static final boolean DEBUG = false;
 
    public CustomFramlayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
 
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new LayoutParams(getContext(),attrs);
    }
 
    @Override
    protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
        return p instanceof LayoutParams ? new LayoutParams((LayoutParams)p):new LayoutParams(p);
    }
 
    @Override
    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
        return p instanceof LayoutParams;
    }
 
    @Override
    protected void onMeasure(int widthSpec, int heightSpec) {
        final int widthMode = MeasureSpec.getMode(widthSpec);
        final int heightMode = MeasureSpec.getMode(heightSpec);
        if (DEBUG && widthMode != MeasureSpec.AT_MOST) {
            Log.w(TAG, "onMeasure: widthSpec " + MeasureSpec.toString(widthSpec) +
                    " should be AT_MOST");
        }
        if (DEBUG && heightMode != MeasureSpec.AT_MOST) {
            Log.w(TAG, "onMeasure: heightSpec " + MeasureSpec.toString(heightSpec) +
                    " should be AT_MOST");
        }
 
        final int widthSize = MeasureSpec.getSize(widthSpec);
        final int heightSize = MeasureSpec.getSize(heightSpec);
        int maxWidth = widthSize;
        int maxHeight = heightSize;
        final int count = getChildCount();
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
 
            if (lp.maxWidth > 0 && lp.maxWidth < maxWidth) {
                maxWidth = lp.maxWidth;
            }
            if (lp.maxHeight > 0 && lp.maxHeight < maxHeight) {
                maxHeight = lp.maxHeight;
            }
        }
 
        final int wPadding = getPaddingLeft() + getPaddingRight();
        final int hPadding = getPaddingTop() + getPaddingBottom();
        maxWidth -= wPadding;
        maxHeight -= hPadding;
 
        int width = widthMode == MeasureSpec.EXACTLY ? widthSize : 0;
        int height = heightMode == MeasureSpec.EXACTLY ? heightSize : 0;
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
 
            final int childWidthSpec = makeChildMeasureSpec(maxWidth, lp.width);
            final int childHeightSpec = makeChildMeasureSpec(maxHeight, lp.height);
 
            child.measure(childWidthSpec, childHeightSpec);
 
            width = Math.max(width, Math.min(child.getMeasuredWidth(), widthSize - wPadding));
            height = Math.max(height, Math.min(child.getMeasuredHeight(), heightSize - hPadding));
        }
        setMeasuredDimension(width + wPadding, height + hPadding);
    }
 
    private int makeChildMeasureSpec(int maxSize, int childDimen) {
        final int mode;
        final int size;
        switch (childDimen) {
            case LayoutParams.WRAP_CONTENT:
                mode = MeasureSpec.AT_MOST;
                size = maxSize;
                break;
            case LayoutParams.MATCH_PARENT:
                mode = MeasureSpec.EXACTLY;
                size = maxSize;
                break;
            default:
                mode = MeasureSpec.EXACTLY;
                size = Math.min(maxSize, childDimen);
                break;
        }
        return MeasureSpec.makeMeasureSpec(size, mode);
    }
 
    public static class LayoutParams extends FrameLayout.LayoutParams {
        @ViewDebug.ExportedProperty(category = "layout")
        public int maxWidth;
 
        @ViewDebug.ExportedProperty(category = "layout")
        public int maxHeight;
 
        public LayoutParams(ViewGroup.LayoutParams other) {
            super(other);
        }
 
        public LayoutParams(LayoutParams other) {
            super(other);
 
            maxWidth = other.maxWidth;
            maxHeight = other.maxHeight;
        }
 
        public LayoutParams(Context c, AttributeSet attrs) {
            super(c, attrs);
 
            final TypedArray a = c.obtainStyledAttributes(attrs,
                    R.styleable.CustomFrameLayoutAttr, 0, 0);
            maxWidth = a.getDimensionPixelSize(
                    R.styleable.CustomFrameLayoutAttr_layout_maxWidth, 0);
            maxHeight = a.getDimensionPixelSize(
                    R.styleable.CustomFrameLayoutAttr_layout_maxHeight, 0);
            a.recycle();
        }
    }
}

使用:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:custom_attr="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.jokerlee.custommaxsizeframelayout.MainActivity">
 
    <com.example.jokerlee.custommaxsizeframelayout.CustomFramlayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
 
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            custom_attr:layout_maxWidth="50dp"
            custom_attr:layout_maxHeight="30dp">
 
            <ImageView
                android:layout_width="350dp"
                android:layout_height="330dp"
                android:layout_gravity="center"
                android:background="@color/material_blue_grey_800"/>
 
        </FrameLayout>
    </com.example.jokerlee.custommaxsizeframelayout.CustomFramlayout>
 
</RelativeLayout>

attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomFrameLayoutAttr">
        <attr name="layout_maxWidth" format="dimension"/>
        <attr name="layout_maxHeight" format="dimension"/>
    </declare-styleable>
</resources>


相关文章
|
13天前
|
Android开发 开发者
安卓开发中的自定义视图:从入门到精通
【9月更文挑战第19天】在安卓开发的广阔天地中,自定义视图是一块充满魔力的土地。它不仅仅是代码的堆砌,更是艺术与科技的完美结合。通过掌握自定义视图,开发者能够打破常规,创造出独一无二的用户界面。本文将带你走进自定义视图的世界,从基础概念到实战应用,一步步展示如何用代码绘出心中的蓝图。无论你是初学者还是有经验的开发者,这篇文章都将为你打开一扇通往创意和效率的大门。让我们一起探索自定义视图的秘密,将你的应用打造成一件艺术品吧!
38 10
|
18天前
|
XML 编解码 Android开发
安卓开发中的自定义视图控件
【9月更文挑战第14天】在安卓开发中,自定义视图控件是一种高级技巧,它可以让开发者根据项目需求创建出独特的用户界面元素。本文将通过一个简单示例,引导你了解如何在安卓项目中实现自定义视图控件,包括创建自定义控件类、处理绘制逻辑以及响应用户交互。无论你是初学者还是有经验的开发者,这篇文章都会为你提供有价值的见解和技巧。
30 3
|
19天前
|
前端开发 Android开发 开发者
安卓应用开发中的自定义视图基础
【9月更文挑战第13天】在安卓开发的广阔天地中,自定义视图是一块神奇的画布,它允许开发者将想象力转化为用户界面的创新元素。本文将带你一探究竟,了解如何从零开始构建自定义视图,包括绘图基础、触摸事件处理,以及性能优化的实用技巧。无论你是想提升应用的视觉吸引力,还是追求更流畅的交互体验,这里都有你需要的金钥匙。
|
22天前
|
缓存 搜索推荐 Android开发
安卓应用开发中的自定义View组件实践
【9月更文挑战第10天】在安卓开发领域,自定义View是提升用户体验和实现界面个性化的重要手段。本文将通过一个实际案例,展示如何在安卓项目中创建和使用自定义View组件,包括设计思路、实现步骤以及可能遇到的问题和解决方案。文章不仅提供了代码示例,还深入探讨了自定义View的性能优化技巧,旨在帮助开发者更好地掌握这一技能。
|
24天前
|
Android开发
Android中SurfaceView的双缓冲机制和普通View叠加问题解决办法
本文介绍了 Android 平台上的 SurfaceView,这是一种高效的图形渲染控件,尤其适用于视频播放、游戏和图形动画等场景。文章详细解释了其双缓冲机制,该机制通过前后缓冲区交换来减少图像闪烁,提升视觉体验。然而,SurfaceView 与普通 View 叠加时可能存在 Z-Order 不一致、同步问题及混合渲染难题。文中提供了使用 TextureView、调整 Z-Order 和创建自定义组合控件等多种解决方案。
56 9
|
28天前
|
Android开发 容器
Android经典实战之如何获取View和ViewGroup的中心点
本文介绍了在Android中如何获取`View`和`ViewGroup`的中心点坐标,包括计算相对坐标和屏幕上的绝对坐标,并提供了示例代码。特别注意在视图未完成测量时可能出现的宽高为0的问题及解决方案。
26 7
|
29天前
|
Android开发
Android经典实战之Textview文字设置不同颜色、下划线、加粗、超链接等效果
本文介绍了 `SpannableString` 在 Android 开发中的强大功能,包括如何在单个字符串中应用多种样式,如颜色、字体大小、风格等,并提供了详细代码示例,展示如何设置文本颜色、添加点击事件等,助你实现丰富文本效果。
71 3
|
26天前
|
前端开发 搜索推荐 Android开发
探索安卓开发中的自定义视图##
【9月更文挑战第6天】 在安卓应用开发的世界里,自定义视图如同绘画艺术中的色彩,它们为界面设计增添了无限可能。通过掌握自定义视图的绘制技巧,开发者能够创造出既符合品牌形象又提升用户体验的独特界面元素。本文将深入浅出地介绍如何从零开始构建一个自定义视图,包括基础框架搭建、关键绘图方法实现、事件处理机制以及性能优化策略。准备好让你的安卓应用与众不同了吗?让我们开始吧! ##
|
1月前
|
图形学 iOS开发 Android开发
从Unity开发到移动平台制胜攻略:全面解析iOS与Android应用发布流程,助你轻松掌握跨平台发布技巧,打造爆款手游不是梦——性能优化、广告集成与内购设置全包含
【8月更文挑战第31天】本书详细介绍了如何在Unity中设置项目以适应移动设备,涵盖性能优化、集成广告及内购功能等关键步骤。通过具体示例和代码片段,指导读者完成iOS和Android应用的打包与发布,确保应用顺利上线并获得成功。无论是性能调整还是平台特定的操作,本书均提供了全面的解决方案。
108 0
下一篇
无影云桌面