3 回答

TA貢獻1793條經驗 獲得超6個贊
最好的選擇是繼承ImageView自己的子類,以覆蓋度量傳遞:
public class SquareImageView extends ImageView {
...
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getMeasuredWidth();
setMeasuredDimension(width, width);
}
...
}

TA貢獻1785條經驗 獲得超4個贊
另一個答案很好。這只是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中執行此操作,
<com.packagepath.tothis.SquareImageView
android:id="@+id/Imageview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
如果您需要不在程序中動態創建ImageView而不是在xml中進行固定,那么此實現將非常有用。

TA貢獻1865條經驗 獲得超7個贊
前面的幾個答案就足夠了。我只是在這里為@Andro Selva和@ a.bertucci的解決方案添加一個小的優化:
這是一個很小的優化,但是檢查寬度和高度是否不同可以防止再次進行測量。
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, widthMeasureSpec);
int width = getMeasuredWidth();
int height = getMeasuredHeight();
// Optimization so we don't measure twice unless we need to
if (width != height) {
setMeasuredDimension(width, width);
}
}
}
- 3 回答
- 0 關注
- 801 瀏覽
添加回答
舉報