繁体   English   中英

如何根据 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

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

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

在此处输入图像描述

正如您在上一个屏幕截图中看到的那样,图像上下有一个空格,因为我手动为ImageView元素指定了一个特定值,这是错误的。

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

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

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

我有一个图像视图,它必须水平填充屏幕,并且它的高度已经自动处理,而不是手动指定 dp 值。

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

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

用于此的 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 但您可以使用背景属性:

android:background="@drawable/carbonara"

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

您可以使用屏幕纵横比来设置图像的高度和宽度。尝试以下功能。` 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;

`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM