没有使用 style 组件情况
<View
android:background="#FF0000"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
使用 style 组件情况
<View
style="@style/myStyle"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<style name="myStyle">
<item name="android:background">
@color/colorAccent
</item>
</style>
这么做有什么好处呢,我们看一看我们在 web 开发时,也有着同样的情况。没有使用 style 的情况就相当于我们把样式写入 html 标签,而 style 就相当于我们把样式定义 css 样式表中,然后在 html 使用 css 样式。好处就是后者复用性更高,我们可以通过 style 将同样样式应用到多个组件。
想象一下,我们计算机有很多 button,我们可以定义 style 来应用到每一个 button,这样一旦要修改样式我们就无需修改每一个 button,而只需要修改 style 就可以了。
不适合应用 style 的情况
<TextView
android:id="@+id/title"
android:textColor="@color/colorAccent"
android:textColorHint="@color/colorPrimary"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/body"
android:textColor="@color/colorAccent"
android:textColorHint="@color/colorPrimary"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
上面示例,我们很容易找出两个textView 共同的样式
android:textColor="@color/colorAccent"
android:textColorHint="@color/colorPrimary"
不过通过 id 分别是 body 和 title 我们了解到这是页面标题和正文两部分内容,由于功能不同,这样不适合我们将同样内容抽取出到 style。
Android studio 提供了提取组件样式来作为 style 使用功能,这样大大地方便了开发人员。在设计设图中选择一个要提取 style 的组件,然后右键单击,在弹出菜单中选择 Refactor 然后选择 Extract Style... ,
完成上面操作,会看到一个 Extract Android Style 对话中,显示了该组件所有的可以提取属性。
我们可以选择要提取到 style 的属性,然后 style name 输入一个 style 名称这样单击 OK 就完成提取
这样我们在 style.xml 文件中就可以看到生成的样式。
<style name="myTextStyle">
<item name="android:textColor">@color/colorAccent</item>
<item name="android:textColorHint">@color/colorPrimary</item>
</style>
我们可以通过一个例子帮助你理解,其实这也没什么不好理解的。
static final int NUM_COLUNM = 3;
static final int NUM_RETRIES = 3;
这里定义了两个静态变量,NUM_COLUMN 表示列表的列数,而 NUM_RETRIES 表示我们进行网络请求通常尝试次数
// static final int NUM_COLUNM = 3;
// static final int NUM_RETRIES = 3;
static final int NUM_THREE = 3
那么我们可不可以将两个暂时具有相同值 3 的静态变量化简为一个 NUM_THREE 呢?显然是不行不同的,这样两个毫不相干的静态变量是无法归结为一个静态变量来表示的。