复习了下自定义style的使用
一、为什么要自定义style
这是样式与控件本身脱离的一种方式。style就像html中的css,只负责自定义样式。View控件在layout中就只负责声明自己就可以了。
就像这样:
首先在style.xml中自定义一个style
<style name="button_style"> <item name="android:background">#fff</item> <item name="android:textSize">30sp</item> <item name="android:textColor">#000</item> </style>
之后我们在activity_layout中调用:
<Button style="@style/button_style" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="测试"/>
所以说如果没有style就只能让View与style属性写在一起,就像这样
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#fff" android:textSize="30dp" android:textColor="#000" android:text="测试"/>
可能这个例子中看不出突出的对比,但是显然当内容庞大的时候第一种方法更好。
缺点:
①、首先这种做法无法复用style。如果其他View也需要复用该style的时候,还需要View自己编写。
②、其次将View与style写在一起是一种很难看的写法,不利于区分。
二、如何自定义style
①、继承android提供的style,继承android提供的style属性
首先,我们可以通过继承android提供预置的style来完成。所以我们讲述一下style的继承
<style name="button_style"> <item name="android:background">#fff</item> <item name="android:textSize">30sp</item> <item name="android:textColor">#000</item> </style> <!--第一种继承方法--> <style name="new_button" parent="button_style"> <item name="android:background">#0ac</item> </style> <!--第二种继承方式--> <style name="button_style.background"> <item name="android:background">#f3e</item> </style>