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