android - 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"
解决方案
您可以在样式中定义属性,如下所示:
<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
. 这将替换现有主题,因此您可能希望将您的主题设置AppTheme
为MyStyle
.
我注意到这样做有一个奇怪的副作用:样式中命名的约束会影响工作室设计器中布局的显示(正确),但约束本身不会显示。布局编辑器也不会发现约束是在样式中定义的,并且会给出“约束缺失”错误。(Android Studio 3.3 RC3)
推荐阅读
- php - PHP Google 插入日历事件 API
- amazon-web-services - AWS Step 函数任务令牌 sendTaskSuccess 跨区域
- python - 在 pandas 中计算 OHLC 数据
- node.js - 在 NodeJS 中创建一个新的目录文件夹
- websocket - 如何在 Jmeter 中编写 Websocket 采样器请求正文
- ios - 在 Swift 中禁用 UISwitch 时,有什么方法可以不使 UISwitch 变灰/淡出?
- css - 使用 Rmarkdown 制作的海报 CSS 文件:需要字体
- amazon-web-services - 无法访问 AWS Elastic beanstalk EC2 实例
- css - 禁用单个表的 css 样式
- c# - 尝试访问自动完成流时出现 COMException (0x80040102)