Android 如何在PercentRelativeLayout中使用layout_aspectRatio?

Android 如何在PercentRelativeLayout中使用layout_aspectRatio?,android,android-layout,android-constraintlayout,android-percentrelativelayout,Android,Android Layout,Android Constraintlayout,Android Percentrelativelayout,我试着在一个视图上实现16:9的纵横比 所以我在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.co

我试着在一个视图上实现16:9的纵横比

所以我在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>

问题:

  • Android Studio警告我:
    应该为
    图像视图定义“布局高度”
  • 当我运行我的项目时,我得到:
    错误:(15)没有找到属性“layout\u aspectRatio”的资源标识符。

那么,出了什么问题?

您似乎使用了错误的依赖项来尝试包含

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

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

compile 'com.android.support:percent:23.1.0'

有了正确的依赖项,您仍然有警告

应定义“布局高度”

我使用了android:layout\u height=“0dp”或android:layout\u width=“0dp”来避免它

           <View
            android:layout_height="0dp"
            android:layout_width="0dp"
            app:layout_aspectRatio="75%"
            app:layout_widthPercent="100%"
             />

你甚至可以使用android:layout\u height=“wrap\u content”,以防内容比layout\u aspectRatio更大,这里有一个g+帖子:这在一定程度上解释了如何使用它


评论中还讨论了布局宽度/高度警告。在未来的Android Studio版本中,将添加一个Lint过滤器,但在此之前,您可以添加一个
来抑制警告,或者忽略它。

现在,由于PercentFrameLayout和PercentRelativeLayout在26.0.0中都被弃用,您可以开始使用

这说明了如何使用ConstraintLayout实现ImageView的16:9纵横比,但它可以应用于任何视图

           <View
            android:layout_height="0dp"
            android:layout_width="0dp"
            app:layout_aspectRatio="75%"
            app:layout_widthPercent="100%"
             />