样式中的ConstraintLayout约束属性

17

如何在样式中使用约束属性?

当我试图像使用其他带有自定义命名空间的属性一样使用它时,它对我的视图没有影响。

 <style name="Header.Center" parent="Header">
    <item name="layout_constraintBottom_toBottomOf">parent</item>
 </style>

添加命名空间app:并没有起到帮助作用。


我已经尝试过它,有点奏效。然而,在您的布局 XML 中,虽然它确实可以正确对齐视图,但仍然会显示警告,即“添加约束条件或视图将在运行时放置在左上角”。在 Android Studio 正确支持此功能之前,我建议完全不要这样做。 - Benjamin Basmaci
1
如果您确保约束正在正确工作,还可以将tools:ignore="MissingConstraints"添加到父约束布局中。 - toffor
2个回答

15

首先,请确保您应用样式的 ViewConstraintLayout 的直接子级。否则,约束将在定位 View 时不被考虑。

我已经尝试过了,您尝试的方法确实可行。我已经将以下样式添加到 styles.xml 中:

<style name="CustomStyle">
    <item name="layout_constraintBottom_toBottomOf">parent</item>
    <item name="layout_constraintEnd_toEndOf">parent</item>
</style>

创建了一个基本的布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="Text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/CustomStyle"/>

</android.support.constraint.ConstraintLayout>

它确实将TextView定位于父视图的右下角。


3
实际上,对我来说删除 app: 才使它正常工作;保留它会导致布局表现异常。 - Antek

2
也许你的视图属性是“match_parent”,但这是错误的。 应该是“wrap_content”。
 <TextView
            android:text="Text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/CustomStyle"/>

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