如何根据 Android 布局中的 layout_width 指定 layout_height 值?

How can I specify the layout_height value based on the layout_width in Android layout?

我绝对是 Android 开发新手,在我开发的第一个应用程序中定位图像时遇到问题。

所以我有以下情况

进入我的布局文件:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Dummy content. -->
    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="0dp">

       <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="300dp"
            android:src="@drawable/carbonara" />

        <TextView android:id="@android:id/text1"
            style="?android:textAppearanceLarge"
            android:textStyle="bold"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="16dp" />

    </LinearLayout>

</ScrollView>

所以,如您所见,有这个 ImageView 元素:

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="300dp"
    android:src="@drawable/carbonara" />

如您所见,对于此 ImageView,我已为宽度和高度设置了以下值

android:layout_width="wrap_content"
android:layout_height="300dp

这是因为我希望图像水平占据所有 space,但我还必须为高度设置一个值。

因此对于之前的值,我得到以下结果:

正如您在前面的屏幕截图中看到的那样,图像上下有一个 space,因为我手动为我的 ImageView 元素赋予了特定值,而这个错了。

我试图设置一个较低的 hwight 值,并且这个空的 space 被删除了 android:layout_height="240dp"值。

但我认为这不是一个好的解决方案,因为它取决于所使用的屏幕。

那么,处理这种情况的最佳方法是什么?

我有一个水平方向必须填满屏幕的图像视图,它的高度已自动处理,无需手动指定 dp 值。

我该如何实现这种行为?我错过了什么?

如果需要重新缩放图片,请尝试使用android:scaleType="centerCrop"android:scaleType="fitXY"

您的问题可以用下面这行简单的代码解决

此 XML 属性是:

android:scaleType="fitCenter"

像下面这样把你的代码放在这里我刚刚添加了新行见#1

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:scaleType="fitCenter"             // #1
    android:layout_height="300dp"
    android:src="@drawable/carbonara" />

你也在使用 src 但你可以使用 background 属性:

android:background="@drawable/carbonara"

您可以使用屏幕纵横比为 image.Try 以下函数设置高度和宽度。` public void calculateAspectRatio() {

int imagewidth;
int imagewidth;
DisplayMetrics displaymetrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);  
             int height = displaymetrics.heightPixels;
            int width = displaymetrics.widthPixels;

             imagewidth=width;
            imageHeight = (imageTwoWidth / 4) * 3;
}

set image height and width

            imageview.requestLayout();
            imageview.getLayoutParams().width = imagewith;//take value from above function for height and width.
            imageview.getLayoutParams().height =imageheight;

`