复习了下自定义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="测试"/>
activity_layout

 所以说如果没有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>
style

两种继承方法都继承了父style的属性,然后通过重写父style的属性。(同JAVA的继承)

那么两个继承方式的区别是什么:

第一种方式是自定义命名。

第二种方式是有阶梯的命名:可以突出自己是修改了parent的哪一部分。

②、自定义View的style

1、自定义一个CustomView(extends View)类

2、编写values/attrs.xml,在其中编写styleable和item等标签元素

<resources>
    <declare-styleable name="CustomView">
        <attr name="custom_bg" format="color"/>
    </declare-styleable>
</resources>
attr

3、使用自定义属性

①、首先可以在style.xml中设定属性

②、在layout中使用Custom的自定属性

4、在CustomView的构造方法中通过TypedArray获取

原文地址:https://www.cnblogs.com/rookiechen/p/5734283.html