【问题标题】:How to match height and width 1:1 in layout android如何在布局android中匹配高度和宽度1:1
【发布时间】:2020-10-30 19:41:01
【问题描述】:

我在 Linearlayout 中有一个图像视图,我希望它的宽度为 fill_parent。我希望它的高度是最终的宽度。例如:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintDimensionRatio="1:1"

    android:scaleType="centerCrop"
    android:layout_margin="2dp"
    tools:ignore="Suspicious0dp" />
</LinearLayout>

但它不显示 android 布局中的图像.. 如果我在代码中强制将 imageview 的高度更改为 100dp,它会起作用,但我想知道为什么即使我写了 constraintDimensionRatio 1:1..

谢谢

【问题讨论】:

    标签: android xml layout height width


    【解决方案1】:

    尝试将weight 添加到您的imageview,然后您将获得height,否则您必须将wrap_content 用作height

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    
    <ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" 
    android:scaleType="centerCrop"
    android:layout_margin="2dp"
    tools:ignore="Suspicious0dp" />
    </LinearLayout>
    
     <!--or if you don't want to use weight then user  height = "wrap_content"-->
    

    【讨论】:

      【解决方案2】:

      您需要使用 ConstraintLayout 作为父级,并将您想要作为主要的维度和另一个维度设置为0dpapp:layout_constraintDimensionRatio="H,1:1" 表示改变高度,使其与宽度为 1:1。

      
       <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
      
            
              <ImageView
                  android:layout_width="match_parent"
                  android:layout_height="0dp"
                  app:layout_constraintDimensionRatio="H,1:1"
                  app:layout_constraintEnd_toEndOf="parent"
                  app:layout_constraintStart_toStartOf="parent"
                  app:layout_constraintTop_toTopOf="parent" />
          </androidx.constraintlayout.widget.ConstraintLayout>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-18
        • 2017-04-03
        • 2019-04-17
        • 1970-01-01
        • 2012-08-17
        • 2013-06-01
        • 1970-01-01
        • 2015-03-31
        相关资源
        最近更新 更多