目的:RecyclerView中item有权重加载的图片需要根据手机尺寸转换成正方形,需要获取到ImageView真实的宽度重新设置高度达到正方形的效果
//注册一个观察者来监听视图树??
ViewTreeObserver viewTreeObserver = mImgIconA.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
mImgIconA.getViewTreeObserver().removeOnGlobalLayoutListener(this);
//获取绘制完之后的宽度
int width = mImgIconA.getMeasuredWidth();
//拿到View的LayoutParams
ViewGroup.LayoutParams layoutParams = mImgIconA.getLayoutParams();
//将他的宽度赋值给高度,这样就是一个正方形了
layoutParams.height = width;
mImgIconA.setLayoutParams(layoutParams);
mImgIconB.setLayoutParams(layoutParams);
mImgIconC.setLayoutParams(layoutParams);
}
});