gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 01:12:35 24 4
gpt4 key购买 nike

我想让我的 ImageView 的大小是基于其宽度的矩形,这是通过覆盖 onGlobalLayout() 并放置 photo.getWidth() 完成的。但它只在竖屏下有效,在横屏下无效。

肖像效果很好:

enter image description here

在风景中,图像不是矩形

enter image description here

这是代码:

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() 中以获得横向宽度,然后它给我相同的值纵向宽度。那么我应该怎么做才能让它在纵向和横向上都能正常工作?

*抱歉英语不好,我也想在这里提高我的英语水平

最佳答案

快速提示:

我不确定这是否是您想要的。根据我的假设,我认为您可能需要使用 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(具有完整的包名称)。

关于android - ImageView.getWidth() 在横向和纵向屏幕中返回相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41908728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com