我希望根据ImageView的宽度使其大小成为矩形,这可以通过重写
onGlobalLayout()
并使用photo.getWidth()
来完成。但是,它只在竖屏屏幕上工作,在横屏屏幕上不起作用。
竖屏正常工作:
在横向模式下,图像不是矩形形状。
这是代码:
fragment_productdetail.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/ivImage0"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="3dp"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:src="@drawable/noimage"/>
<ImageView
android:id="@+id/ivImage1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="3dp"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:src="@drawable/noimage"/>
<ImageView
android:id="@+id/ivImage2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="3dp"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:src="@drawable/noimage"/>
<ImageView
android:id="@+id/ivImage3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="3dp"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:src="@drawable/noimage"/>
</LinearLayout>
FragmentProductDetail.java
ivPhotos[0] = (ImageView) inflatedView.findViewById(R.id.ivImage0);
ivPhotos[1] = (ImageView) inflatedView.findViewById(R.id.ivImage1);
ivPhotos[2] = (ImageView) inflatedView.findViewById(R.id.ivImage2);
ivPhotos[3] = (ImageView) inflatedView.findViewById(R.id.ivImage3);
for (final ImageView photo : ivPhotos) {
photo.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
photo.getViewTreeObserver().removeOnGlobalLayoutListener(this);
photo.getLayoutParams().height = photo.getWidth();
}
});
}
然后我尝试将Log.i("zihad", ""+photo.getWidth());
放在onGlobalLayout()里以获取横屏宽度,但是它给我提供了相同的纵向宽度。那么我该怎么做才能使它在纵向和横向都起作用呢?
*很抱歉我的英语不好,我也在这里提问以改善我的英语。