另一个答案很好。这只是bertucci解决方案的扩展,以使ImageView相对于xml膨胀版式具有正方形的宽度和高度。
创建一个类,说一个SquareImageView这样扩展ImageView,
public class SquareImageView extends ImageView {
public SquareImageView(Context context) {
super(context);
}
public SquareImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getMeasuredWidth();
setMeasuredDimension(width, width);
}
}
现在,在您的xml中执行此操作,
android:id="@+id/Imageview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
如果您需要不在程序中动态创建ImageView而不是在xml中进行固定,那么此实现将非常有用。