您的位置:首页 > 移动开发 > Android开发

Style简单使用

2017-07-01 13:40 85 查看
使用Style的目的是为了统一风格,摒弃重复的代码,其实本质上Theme也是Style

1 使用场景

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/empty1"
android:gravity="center"
android:text="您的列表空空如也"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:id="@+id/empty2"
android:gravity="center"
android:text="您的列表空空如也"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:id="@+id/empty3"
android:gravity="center"
android:text="您的列表空空如也"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>


如上图所示,你会发现这三个TextView除了id不一样之外,其他的属性都一样,但是你又不得不重复写三遍,这还不是噩梦的开始,这只是在一个布局,其他的布局你是不是也有类似的代码?万一有一天Boss觉得对齐方式改为左对齐比较好,你是不是需要一个一个TextView里面修改呢?对,这就是代码不面向对象的坏处,缺乏重用性,不利于维护

2 Style闪亮登场

1 打开res->values->styles文件

2 自定义自己的Style

<style name="TextStyle" >
<item name="android:layout_height">match_parent</item>
<item name="android:text">您的列表空空如也</item>
<item name="android:gravity">center</item>
<item name="android:layout_width">match_parent</item>
</style>


3 在布局文件中引用即可

<TextView
android:id="@+id/empty1"
style="@style/TextStyle" />
<TextView
android:id="@+id/empty2"
style="@style/TextStyle" />
<TextView
android:id="@+id/empty3"
style="@style/TextStyle" />


3 总结好处

1 封装统一风格的属性,比如我要求TextView统一左对齐,间隔2dp,大家都用这个风格就统一了样式

2 易于维护,比如现在你的老板让你把text改成“我好帅”,你不用每个TextView里面改了,直接去Style中修改即可,非常方便
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android style