首页 > 解决方案 > ConstraintLayout 子项的样式

问题描述

我想为我的内部元素设置一般样式ConstraintLayout。例如,我有多个TextView具有以下属性的 s:

    <TextView
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_marginLeft="8dp"
      android:layout_marginRight="8dp"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"/>

我为它创造了这种风格:

    <style name="PageTitleStyle">
      <item name="android:layout_width">0dp</item>
      <item name="android:layout_height">wrap_content</item>
      <item name="android:layout_marginRight">8dp</item>
      <item name="android:layout_marginLeft">8dp</item>
   </style>

但是如何将这些属性设置为定义的样式?

       app:layout_constraintLeft_toLeftOf="parent"
       app:layout_constraintRight_toRightOf="parent"

标签: androidandroid-layoutandroid-stylesandroid-constraintlayout

解决方案


您可以在样式中定义属性,如下所示:

<style name="MyStyle">
    <item name="layout_constraintLeft_toLeftOf">parent</item>
    <item name="layout_constraintRight_toRightOf">parent</item>
</style>

然后,您可以style="@style/MyStyle"在每个TextView.

除非您将样式设置为主题,否则在 上设置样式ConstraintLayout不会在子级上设置样式。ConstraintLayout请参阅“将样式应用为主题”。(重点是我的。)

从 Android 5.0(API 级别 21)和 Android 支持库 v22.1 开始,您还可以在布局文件中为视图指定 android:theme 属性。这会修改该视图和任何子视图的主题,这对于更改界面特定部分的主题调色板很有用。

所以你会添加android:theme="@style/MyStyle"ConstraintLayout. 这将替换现有主题,因此您可能希望将您的主题设置AppThemeMyStyle.

我注意到这样做有一个奇怪的副作用:样式中命名的约束会影响工作室设计器中布局的显示(正确),但约束本身不会显示。布局编辑器也不会发现约束是在样式中定义的,并且会给出“约束缺失”错误。(Android Studio 3.3 RC3)


推荐阅读