【问题标题】:PercentFrameLayout: You must supply a layout_width attributePercentFrameLayout:您必须提供 layout_width 属性
【发布时间】:2016-01-21 18:01:47
【问题描述】:

我尝试使用PercentFrameLayout,但收到以下错误消息:

Binary XML file line #: You must supply a layout_width attribute.

这是我使用的xml:

<android.support.percent.PercentFrameLayout
    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="match_parent">

    <ImageView
        app:layout_heightPercent="50%"
        app:layout_marginLeftPercent="25%"
        app:layout_marginTopPercent="25%"
        app:layout_widthPercent="50%"/>
</android.support.percent.PercentFrameLayout>

这是一个错误还是我的错误?

【问题讨论】:

  • 这看起来与developer.android.com/reference/android/support/percent/… 的示例完全一样,除了参数的顺序,所以我认为它是正确的。你确定这些是有问题的观点吗?如果您删除这些视图,您的布局是否正确加载?
  • @CoryCharlton 是的,它来自文档,是的,它是有问题的视图。 Android Studio 也将其突出显示为一个问题。

标签: android android-layout android-percent-library android-percent-layout


【解决方案1】:

由于 XML 布局规范,layout_widthlayout_height 属性仍然是必需的,但在 PercentFrameLayoutPercentRelativeLayout 中实际上被忽略了。

您只需将值设置为0dpwrap_content

<ImageView
    android:layout_height="0dp"
    android:layout_width="0dp"
    app:layout_heightPercent="50%"
    app:layout_marginLeftPercent="25%"
    app:layout_marginTopPercent="25%"
    app:layout_widthPercent="50%" />

这类似于使用标准LinearLayoutlayout_weight,您也必须指定layout_width

【讨论】:

  • 但是文档说It is not necessary to specify layout_width/height if you specify layout_widthPercent.
  • @RalphBergmann 这很奇怪,如果不指定宽度/高度,我什至无法编译 XML。所以我不确定文档是否正确。
  • 看起来很有必要——我试过省略宽度/高度(没有抛出异常),只能通过将两个值都设置为 0dp 来正确渲染。