我为 style 和 theme 而狂(1)

作者 : 开心源码 本文共1820个字,预计阅读时间需要5分钟 发布时间: 2022-05-12 共269人阅读

没有使用 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… ,

001.JPG
完成上面操作,会看到一个 Extract Android Style 对话中,显示了该组件所有的可以提取属性。
002.JPG
我们可以选择要提取到 style 的属性,而后 style name 输入一个 style 名称这样单击 OK 就完成提取
003.JPG
这样我们在 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 呢?显然是不行不同的,这样两个毫不相干的静态变量是无法归结为一个静态变量来表示的。

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » 我为 style 和 theme 而狂(1)

发表回复