ImageView.getWidth()在横向和纵向屏幕中返回相同的值

时间:2017-01-28 10:31:55

标签: android

我想让我的ImageView的大小根据其宽度呈矩形,并且完成了SimpleDateFormat并放置onGlobalLayout()。但它仅适用于纵向屏幕,而不适用于横向屏幕。

肖像工作正常:

enter image description here

在横向中,图像不是矩形的

enter image description here

这是代码:

fragment_productdetail.xml

photo.getWidth()

FragmentProductDetail.java

<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>

然后我尝试将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(); } }); } 放在onGlobalLayout()中以获取横向宽度,然后它在纵向中给出了相同的宽度值。那么我该怎样做才能使它在肖像和风景中运作?

*对不起英语不好,我也在这里要求提高英语水平

1 个答案:

答案 0 :(得分:1)

快速提示:

我不确定,如果这是你想要的。根据我的假设,我认为您可能需要使用Square ImageView进行布局。如果您在渲染后尝试更改布局,则应在设置其高度之前调用photo.requestLayout();

另一种解决方案是使用SquareImageView。要实现这一点,只需创建一个扩展ImageView的View,并通过覆盖它的onMeasure来设置高度。

public class MyImageView extends ImageView {

 @Override
 public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  int width = getMeasuredWidth();
  setMeasuredDimension(width, width);
}

现在在您的布局中,将ImageView替换为MyImageView(包含完整的包名)。

相关问题