我正試圖根據相對佈局創建自定義佈局「SquareBox」,以將ImageView放在中間。 而這個自定義佈局將總是在正方形大小(取決於ImageView的高度和寬度)。父中的中心不適用於自定義相對佈局
protected void onMeasure(int width, int height) {
super.onMeasure(width, height);
int measuredWidth = getMeasuredWidth();
int measuredHeight = getMeasuredHeight();
int size;
if (measuredWidth > measuredHeight) {
size = measuredWidth;
} else {
size = measuredHeight;
}
setMeasuredDimension(size, size);
}
這裏是我的佈局代碼:
<com.example.tools.SquareBox
android:id="@+id/square_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:background="@android:color/darker_gray">
<ImageView
android:id="@+id/canvas_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:layout_centerInParent="true"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
tools:src="@drawable/demo_image" />
</com.example.tools.SquareBox>
它工作正常,但圖像的視圖是不是在這個自定義視圖的中心。 我試過以下內容: - > android:layout_centerInParent =「true」用於ImageView。
- > android:gravity =「center」爲「SquareBox」。
- >以編程方式將CENTER_IN_PARENT添加到SquareBox的onMeasure方法中的ImageView中。
但沒有任何工作。 我在這裏失蹤了什麼?
我已經嘗試過這個。但不工作。 –