继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

我为 style 和 theme 而狂(1)

幕布斯6054654
关注TA
已关注
手记 1135
粉丝 218
获赞 1009

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

https://img4.mukewang.com/5d2d25020001abef04330326.jpg

001.JPG


完成上面操作,会看到一个 Extract Android Style 对话中,显示了该组件所有的可以提取属性。

https://img.mukewang.com/5d2d25060001ad4c05080383.jpg

002.JPG


我们可以选择要提取到 style 的属性,然后 style name 输入一个 style 名称这样单击 OK 就完成提取

https://img4.mukewang.com/5d2d250b00017d5205010421.jpg

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



作者:zidea
链接:https://www.jianshu.com/p/b0de50721c4d


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP