安卓 - 使用dimens实现ConstraintLayout百分比布局

18

有一个问题如何使用百分比值使 ConstraintLayout 生效?,它的答案展示了如何使用百分比:

<android.support.constraint.Guideline
    android:id="@+id/guideline"
    android:layout_width="1dp"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.5"/>

但是如果你不想硬编码百分比而是使用dimen资源,它将无法工作。

<!-- inside the layout -->

<android.support.constraint.Guideline
    android:id="@+id/guideline"
    android:layout_width="1dp"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="@dimen/guideline_perc"/>

<!-- inside dimens.xml -->

<dimen name="guideline_perc>0.5</dimen>
您会收到以下错误:
Float types not allowed (at 'guideline_perc' with value 0.5).

如果您将该值替换为1,则会返回类似的错误:
Integer types not allowed (at 'guideline_perc' with value 1).

如何设置百分比而不是硬编码到布局中?
4个回答

15

不要使用dimen资源,而是使用类型为dimen的item资源:

<item name="guideline_perc" type="dimen">0.5</item>

如果使用整数,最好使用integer资源:

<integer name="guideline_perc">1</integer>


1
如果这个可以工作,那么这要么是IDE的错误,要么是构建工具的错误,因为两种方法都会导致一个维度资源。 - CommonsWare
1
将资源定义为dimen需要一个度量单位。将其定义为类型为“dimen”的项则不需要。此外,可以添加格式“float”,但不是必需的。 - neits
1
使用 integer 会是更好的解决方案,没错,但在这个例子中我正在使用一个浮点数,据我所知并没有 float 资源。 - neits
1
不好意思,那个方法行不通。虽然AS没有报错,而且预览中布局看起来也没问题,但是编译不通过。需要使用这个:<item name="guideline_perc" type="dimen" format="float">0.67</item> - AutonomousApps
1
我该如何引用这个? - DaniloDeQueiroz
显示剩余3条评论

13

使用分数语法来设置百分比

<fraction name="guideline_perc">0.5</fraction>

然后

app:layout_constraintGuide_percent="@fraction/guideline_perc"

3
小提示:令人困惑的是,XML编辑器不提供_typeAhead_。只有在你完全正确地拼写资源名称时,红灯才会熄灭。 - Bad Loser

1
现在在2021年,dimen float运作良好。 只是在这种情况下,在Android Studio中的自动完成功能没有起作用。不知道为什么。 < p > < code > app:layout_constraintGuide_percent =“@ dimen / guideline_perc”


0

由系统自动生成

<item name="porcent_line_top_navebar" type="dimen" format="float">0.88</item>


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