如何在PercentRelativeLayout中使用layout_aspectRatio?

Pie*_*rre 13 android android-layout android-constraintlayout android-percentrelativelayout

我尝试在视图上实现16:9的宽高比PercentRelativeLayout.

所以我把这行放在build.gradle文件中: compile 'com.android.support:design:23.0.1'

我用这个布局:

<android.support.percent.PercentRelativeLayout
    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="wrap_content">

    <ImageView
        android:layout_width="match_parent"
        app:layout_aspectRatio="178%"
        android:scaleType="centerCrop"/>

</android.support.percent.PercentRelativeLayout>
Run Code Online (Sandbox Code Playgroud)

问题:

  • Android Studio警告我:'layout_height' should be defined为了ImageView.
  • 当我运行我的项目时,我得到了:Error:(15) No resource identifier found for attribute 'layout_aspectRatio'.

那有什么不对?

MH.*_*MH. 13

在尝试包含百分比支持库时,您似乎使用了错误的依赖项.

正确的(和最新版本)是:

com.android.support:percent:23.1.0
Run Code Online (Sandbox Code Playgroud)

换句话说,声明的依赖项应该在gradle文件中如下所示:

compile 'com.android.support:percent:23.1.0'
Run Code Online (Sandbox Code Playgroud)


小智 13

有了正确的依赖关系,你仍然有警告

应该定义'layout_height'

我使用android:layout_height ="0dp"或android:layout_width ="0dp"来避免它.

           <View
            android:layout_height="0dp"
            android:layout_width="0dp"
            app:layout_aspectRatio="75%"
            app:layout_widthPercent="100%"
             />
Run Code Online (Sandbox Code Playgroud)

你甚至可以使用android:layout_height ="wrap_content",如果内容会比layout_aspectRatio更大


Eug*_*sov 3

现在,随着 PercentFrameLayout 和 PercentRelativeLayout 在 26.0.0 中被弃用,您可以开始使用ConstraintLayout

这篇博客文章解释了如何使用 ConstraintLayout 实现 ImageView 的 16:9 宽高比,但它可以应用于任何视图。