Android正方形View
16lz
2021-01-26
在Android开发中有时候我们需要方形的View,即宽高相等的View,一般需要正方形的ImageView的情形可能会更多一些。
下面介绍自定义正方形的View(ImageVIew也是一样)。
定义一个SquareView继承View,重写构造方法。重点是重写onMeasure方法。
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); Log.e("tag", "onMeasure: widthMode=" + widthMode + " heightMode=" + heightMode); //如果宽度指定特定值,并且高度未指定特定值(让高度等于宽度就保证了宽高相等) if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY) { int width = MeasureSpec.getSize(widthMeasureSpec); int height = width; if (heightMode == MeasureSpec.AT_MOST) {//这里还考虑了高度受上限的情况(比如父容器固定了高度) height = Math.min(height, MeasureSpec.getSize(heightMeasureSpec)); } setMeasuredDimension(width, height); } else { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }
重写onMeasure方法就完成了,主要逻辑就是,用户指定View的宽度值,不指定高度具体值,onMeasure中设置高度等于宽度。
下面针对这个逻辑我们在布局中测试验证一下,看看我们的正方形View的效果如何。
<?xml version="1.0" encoding="utf-8"?>
我们针对不同的情况对我们的SquareView做了测试,效果如下:
从效果图可以看出,只有宽度固定,高度不固定的情况是正方形的(跟我们onMeasure中的逻辑符合)。
到此我们的正方形View就完成了,使用时,坚持宽度固定值,高度不指定的原则就可以了。
下面给出SquareView的代码
public class SquareView extends View { public SquareView(Context context) { super(context); } public SquareView(Context context, AttributeSet attrs) { super(context, attrs); } public SquareView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); //如果宽度指定特定值,并且高度未指定特定值(让高度等于宽度就保证了宽高相等) if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY) { int width = MeasureSpec.getSize(widthMeasureSpec); int height = width; if (heightMode == MeasureSpec.AT_MOST) {//这里还考虑了高度受上限的情况(比如父容器固定了高度) height = Math.min(height, MeasureSpec.getSize(heightMeasureSpec)); } setMeasuredDimension(width, height); } else { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }}
更多相关文章
- Android(安卓)ApiDemos示例解析(127):Views->Layout Animation->
- Android(安卓)在OnCreate获取需要控件的高度,宽度,textview的行数
- Android(安卓)自定义侧边栏列表
- 上中下布局,上下高度指定,中间自适应(左中右同理)
- android PinYinIME横屏模式禁止全屏输入 & 调整横屏模式下键盘高
- Android网络安全之NetworkSecurityConfig
- 关于ListView嵌套的问题
- Android(安卓)RecyclerView实现图片自适应高度的瀑布流
- android 获取字符串在屏幕中所占像素宽度和高度