样式和android:theme属性之间有什么区别? [英] What is the difference between style and android:theme attributes?

查看:214
本文介绍了样式和android:theme属性之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用于Android布局xml文件中的buttonstextviews之类的视图的android:themestyle属性之间的主要区别是什么?

如何使用它们?

以及何时使用哪个?

解决方案

有两个主要区别:

首先,通过style分配给视图的属性将仅应用于该视图,而通过android:theme分配给该视图的属性将应用于该视图及其所有子级.例如,考虑以下样式资源:

<style name="my_background">
    <item name="android:background">@drawable/gradient</item>
</style>

如果使用style="@style/my_background"将其应用于具有三个子级TextViewLinearLayout,则linearlayout将使用渐变背景进行绘制,但文本视图的背景将保持不变.

如果相反,我们使用android:theme="@style/my_background"将其应用于LinearLayout,则linearlayout和三个文本视图中的每一个都将使用渐变作为背景.

第二个主要区别是,某些属性仅在视图主题中定义时才会影响视图.例如,考虑以下样式资源:

<style name="checkboxes">
    <item name="colorAccent">#caf</item>
    <item name="colorControlNormal">#caf</item>
</style>

如果我使用style="@style/checkboxes"将其应用于CheckBox,则不会发生任何事情.相反,如果我使用android:theme="@style/checkboxes"应用它,则复选框的颜色将更改.

就像第一个规则说的那样,包含主题属性的样式将应用于具有android:theme属性的视图的所有子级.因此,我可以通过对我的linearlayout应用android:theme="@style/checkboxes"来更改linearlayout中所有复选框的颜色.

What are the key differences between android:theme and style attributes used for views like buttons and textviews in android layout xml files?

How to use them?

and When to use which?

解决方案

There are two key differences:

First, attributes assigned to a view via style will apply only to that view, while attributes assigned to it via android:theme will apply to that view as well as all of its children. For example, consider this style resource:

<style name="my_background">
    <item name="android:background">@drawable/gradient</item>
</style>

If we apply it to a LinearLayout with three child TextViews by using style="@style/my_background", then the linearlayout will draw with a gradient background, but the backgrounds of the textviews will be unchanged.

If instead we apply it to the LinearLayout using android:theme="@style/my_background" then the linearlayout and each of the three textviews will all use the gradient for their background.

The second key difference is that some attributes only affect views if they are defined in that view's theme. For example, consider this style resource:

<style name="checkboxes">
    <item name="colorAccent">#caf</item>
    <item name="colorControlNormal">#caf</item>
</style>

If I apply this to a CheckBox using style="@style/checkboxes", nothing will happen. If instead I apply it using android:theme="@style/checkboxes", the color of the checkbox will change.

Just like the first rule said, styles containing theme attributes will apply to all children of the view with the android:theme attribute. So I can change the color of all checkboxes in a linearlayout by applying android:theme="@style/checkboxes" to my linearlayout.

这篇关于样式和android:theme属性之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆