一般用于不确定尺寸的方形的图片布局,只需要将此布局套在ImageView(或者其他控件)外面即可:
比如说:
<com.dome.widget.SquareLayout
android:layout_margin="10dp"
android:layout_width="80dp"
android:layout_height="80dp">
<ImageView
android:id="@+id/appoin_search_styleimage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
/>
</com.dome.widget.SquareLayout>
我们在适配屏幕的时候很有用,不在担心控件显示在不同的手机上效果不同了。。。
public class SquareLayout extends RelativeLayout {
public SquareLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public SquareLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareLayout(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getMeasuredWidth();
int height = getMeasuredHeight();
if (height != width) {
// 强制让高度等于宽度,重新布局(这里是宽高相等,你也可以指定比例就ok了)
height = width;
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}