在代碼中對 ImageView 設定 LayoutParams、setMaxHeight 等均無效,圖片尺寸不變。
ImageView img = findViewById(R.id.image);
// 錯誤 1:直接修改 getLayoutParams() 回傳物件 (可能為 null 或非預期類型)
img.getLayoutParams().height = 200;
// 錯誤 2:用錯誤的 LayoutParams 類型 (父容器是 RelativeLayout 卻用 LinearLayout.LayoutParams)
img.setLayoutParams(new LinearLayout.LayoutParams(100, 100));
// 錯誤 3:setMaxHeight 僅限制最大值,不強制設定尺寸
img.setMaxHeight(100);
ImageView img = findViewById(R.id.image);
// 情況 1:父容器是 LinearLayout
img.setLayoutParams(new LinearLayout.LayoutParams(200, 200));
// 情況 2:父容器是 RelativeLayout
img.setLayoutParams(new RelativeLayout.LayoutParams(200, 200));
// 情況 3:父容器是 FrameLayout / ViewGroup 通用
img.setLayoutParams(new ViewGroup.LayoutParams(200, 200));
// 情況 4:支援邊距 (Margin) - 需用 MarginLayoutParams 子類
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(200, 200);
params.setMargins(16, 16, 16, 16); // left, top, right, bottom
img.setLayoutParams(params);
public void setImageViewSize(ImageView img, int dpSize, int marginDp) {
// 1. dp 轉 px
float density = img.getContext().getResources().getDisplayMetrics().density;
int pxSize = Math.round(dpSize * density);
int pxMargin = Math.round(marginDp * density);
// 2. 根據父容器建立正確 LayoutParams
ViewGroup.LayoutParams lp = img.getLayoutParams();
if (lp instanceof LinearLayout.LayoutParams) {
LinearLayout.LayoutParams llp = (LinearLayout.LayoutParams) lp;
llp.width = pxSize;
llp.height = pxSize;
llp.setMargins(pxMargin, pxMargin, pxMargin, pxMargin);
img.setLayoutParams(llp);
} else if (lp instanceof RelativeLayout.LayoutParams) {
RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) lp;
rlp.width = pxSize;
rlp.height = pxSize;
rlp.setMargins(pxMargin, pxMargin, pxMargin, pxMargin);
img.setLayoutParams(rlp);
} else {
// 通用 fallback
img.setLayoutParams(new ViewGroup.LayoutParams(pxSize, pxSize));
}
// 3. 設定縮放類型避免變形
img.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
LinearLayout 子 View 用 LinearLayout.LayoutParams,以此類推lp.width 後需 setLayoutParams(lp) 生效CENTER_CROP、FIT_CENTER 等控制圖片填充方式<ImageView
android:id="@+id/image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="16dp"
android:scaleType="centerCrop"
android:src="@drawable/placeholder" />
靜態尺寸優先用 XML,動態計算尺寸才用代碼設定。