12

我試圖在PercentRelativeLayout的視圖上實現16:9的寬高比。如何在PercentRelativeLayout中使用layout_aspectRatio?

所以我已經把這個線在我的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中警告我:'layout_height' should be definedImageView
  • 當我運行我的項目時,我得到:Error:(15) No resource identifier found for attribute 'layout_aspectRatio'

那麼,怎麼了?

回答

1

現在在26.0.0中已棄用PercentFrameLayout和PercentRelativeLayout,您可以開始使用ConstraintLayout

這個blog article解釋瞭如何使用ConstraintLayout實現ImageView的16:9寬高比,但它可以應用於任何視圖。

13

看來你使用錯誤的依賴關係來試圖包含Percent Support Library

正確的一個(最新版本)是:

com.android.support:percent:23.1.0 

換句話說,該聲明的依賴性看起來應該像這樣在你的gradle這個文件:

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

如果我正在爲API22構建,我該怎麼辦?我不能使用23.1.0的權利?包括'com.android.support:support-v4:22.2.0'和'com.android.support:percent:22.2.0'給了我同樣的錯誤。 – ShahiM

+2

@ShahiM:我不明白你爲什麼不能在API22中使用'23.1.0'--事實上,我很肯定我自己是這麼做的。與appcompat一樣,您可能確實需要使用構建工具版本23.0.0-23.0.2,但這不應該干擾您的targetSdkVersion。 –

+0

感謝您的提示。會嘗試一下。 – ShahiM

13

有了正確的依賴仍然發出警告

'layout_height'should be defined

我用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%" 
      /> 

你甚至可以使用Android:layout_height =「WRAP_CONTENT」中的內容的情況下,將更大的layout_aspectRatio

3

有一個G +張貼在這裏:解釋如何在一定的深度使用此https://plus.google.com/+AndroidDevelopers/posts/ZQS29a5yroK

在評論中還有關於layout_width/height警告的討論。在未來的Android Studio版本中會添加一個Lint篩選器,但在此之前您可以添加一個<!-- suppress AndroidDomInspection -->來抑制警告,或者忽略它。