百分比布局:您必须提供一个layout_width属性。

6

我尝试使用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>

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


那看起来和 http://developer.android.com/reference/android/support/percent/PercentFrameLayout.html 的例子完全一样,除了参数的顺序不同,所以我认为它是正确的。你确定那些是有问题的视图吗?如果你移除那些视图,你的布局能够正确加载吗? - Cory Charlton
@CoryCharlton 是的,这来自文档,并且是出问题的视图。Android Studio也将其标记为问题。 - Ralph Bergmann
1个回答

4
layout_widthlayout_height属性在XML布局规范中仍然是必须的,但在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

但是文档说:“如果您指定了layout_widthPercent,则不需要指定layout_width/height。” - Ralph Bergmann
@RalphBergmann 这很奇怪,我甚至在没有指定宽度/高度的情况下无法编译XML..因此我不确定文档是否正确。 - Floern
看起来是必要的 - 我已经尝试省略宽度/高度(没有抛出异常),只有将两个值都设置为0dp才能正确渲染。 - Rachael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接