ImageView显示图片的控件,应用中使用比较频繁,当需要显示的图片宽高相等时除了固定宽高,还可以自定义ImageView,重写onMeasure()方法,这个方法主要是可以测量控件的大小,实现宽高相等。直接上代码
public class WHImageView extends android.support.v7.widget.AppCompatImageView {
public WHImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public WHImageView(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 设置View宽高的测量值
setMeasuredDimension(getDefaultSize(0, widthMeasureSpec),
getDefaultSize(0, heightMeasureSpec));
// 只有setMeasuredDimension调用之后,才能使用getMeasuredWidth()和getMeasuredHeight()来获取视图测量出的宽高,以此之前调用这两个方法得到的值都会是0
int childWidthSize = getMeasuredWidth();
// 高度和宽度一样
heightMeasureSpec = widthMeasureSpec = MeasureSpec.makeMeasureSpec(
childWidthSize, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
那么在什么时候会用到这个呢,这里举两个例子
- RecyclerView中GridLayoutManager布局,一行显示多张图片时,宽度设置wrap_content,那么高度再设置wrap_content时就需要宽高相等,比如淘宝中的评价拍照
- 头像显示,比如淘宝头像点击放大效果