【问题标题】:Can an Android view have an aspect ratio, fill the parent horizontally and be centered in the parent?Android 视图可以具有纵横比,水平填充父级并在父级中居中吗?
【发布时间】:2017-06-07 19:33:17
【问题描述】:

我正在尝试在 RecyclerView 的行之间嵌入图像(作为另一个 ViewType/ViewHolder)。所述图像必须具有 9:5 纵横比,最大高度为 600 像素,因此它不会在更大的手机或平板电脑上变得很大,因此如果由于纵横比其尺寸与父宽度不匹配,则必须水平居中调整大小。

如果没有自定义代码,这是否可以实现?我尝试了 ConstraintLayout 和 PercentFrameLayout 似乎都忽略了 android:maxHeight 标准。

【问题讨论】:

  • 最大高度为 600 像素 - 你实际上并不想要那个。你想要一个以 dp 为单位的最大高度。以 px 做实际上并不能控制它有多大,在高密度显示器上它将是低密度显示器的 1/4。
  • @GabeSechan 有效的批评,在真正让所有其他标准发挥作用后,我会考虑这一点。
  • 我通常会在显示图像后调整图像大小(也在 RecyclerView 中)。在这种情况下,我得到一个图像宽度,计算它的高度并设置。

标签: android android-layout


【解决方案1】:

您可以使用指南通过ConstraintLayout 执行此操作。将您的准则 600px 分开,并将 ImageView 约束到准则:顶部和底部。这些约束将阻止图像超过600px。这是一个video,当我上下移动底部指南时会发生什么。下面是布局的 XML。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="match_parent"
    tools:context="com.example.myapplication.MainActivity">

    <android.support.constraint.Guideline
        android:id="@+id/guidelineTop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_begin="0px" />

    <android.support.constraint.Guideline
        android:id="@+id/guidelineBottom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_begin="600px" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="0dp"
        app:layout_constraintBottom_toTopOf="@+id/guidelineBottom"
        app:layout_constraintDimensionRatio="9:5"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guidelineTop"
        app:srcCompat="@mipmap/ic_launcher"/>

</android.support.constraint.ConstraintLayout>

【讨论】:

    猜你喜欢
    • 2020-03-16
    • 2017-09-20
    • 1970-01-01
    • 2012-03-26
    • 2018-10-21
    • 2013-11-18
    • 1970-01-01
    • 2017-11-16
    • 2010-12-30
    相关资源
    最近更新 更多