How to use layout_aspectRatio in the PercentRelativeLayout?

偶尔善良 提交于 2019-12-06 18:33:33

问题


I try to achieve a 16:9 aspect ratio on a view with the PercentRelativeLayout.

So I have put this line in my build.gradle file: compile 'com.android.support:design:23.0.1'

I use this layout:

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

Problems:

  • Android Studio warn me with: 'layout_height' should be defined for the ImageView.
  • When I run my project I got : Error:(15) No resource identifier found for attribute 'layout_aspectRatio'.

So what's wrong ?


回答1:


Now with both PercentFrameLayout and PercentRelativeLayout being deprecated in 26.0.0, you can start using ConstraintLayout.

This blog article explains how to achieve a 16:9 aspect ratio for ImageView using ConstraintLayout, but it can be applied to any view.




回答2:


It appears you're using the wrong dependency in an attempt to include the Percent Support Library.

The correct one (and latest version) is:

com.android.support:percent:23.1.0

In other words, the declared dependency should look like this in your gradle file:

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



回答3:


With the correct dependency you still had the warn

'layout_height' should be defined

I used android:layout_height="0dp" or android:layout_width="0dp" to avoid it.

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

you can even use android:layout_height="wrap_content" in case of the content will be bigger that the layout_aspectRatio




回答4:


There is a g+ post here: https://plus.google.com/+AndroidDevelopers/posts/ZQS29a5yroK that explains how to use this in some depth.

In the comments there's also a discussion about the layout_width/height warning. A Lint filter will be added in a future Android Studio version, but until then you can add a <!-- suppress AndroidDomInspection --> to suppress the warning, or just ignore it.



来源:https://stackoverflow.com/questions/33415492/how-to-use-layout-aspectratio-in-the-percentrelativelayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!