android Button源码分析

来源:互联网 发布:pkpm建筑设计软件 编辑:程序博客网 时间:2024/06/10 12:52

在Android中Button是一个非常常用的控件,下面我们就一起来分析一下Button源代码。

1 Button.java

 Button的源代码如下,非常简单几个构造器,它继承自TextView,添加了一个默认的com.android.internal.R.attr.buttonStyle样式。如果有时间可以学习一下TextView的源码

public class Button extends TextView {

    publicButton(Context context) {

        this(context,null);

    }

 

    publicButton(Context context, AttributeSet attrs) {

        this(context, attrs, com.android.internal.R.attr.buttonStyle);

    }

 

    publicButton(Context context, AttributeSet attrs,int defStyle) {

        super(context, attrs, defStyle);

    }

}

2 styles.xml

在android源码的styles.xml文件中关于Button的样式:

<style name="Widget.Button">

        <item name="android:background">@android:drawable/btn_default</item>

        <item name="android:focusable">true</item>

        <item name="android:clickable">true</item>

        <item name="android:textAppearance">?android:attr/textAppearanceSmallInverse</item>

        <item name="android:textColor">@android:color/primary_text_light</item>

        <item name="android:gravity">center_vertical|center_horizontal</item>

</style>

 

<style name="Widget.Button.Small">

        <item name="android:background">@android:drawable/btn_default_small</item>

</style>

 

 <style name="Widget.Button.Inset">

        <item name="android:background">@android:drawable/button_inset</item>

</style>

 

<style name="Widget.Button.Transparent">

        <item name="android:background">@android:drawable/btn_default_transparent</item>

        <item name="android:textAppearance">?android:attr/textAppearanceSmall</item>

        <item name="android:textColor">@android:color/white</item>

</style>

这里我们能看到button各种获取焦点、被按下的各种样式是由btn_default、btn_default_small、button_inset、btn_default_transparent这几个xml文件来控制。

 

3 btn_default.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_window_focused="false" android:state_enabled="true"

        android:drawable="@drawable/btn_default_normal" />

    <item android:state_window_focused="false" android:state_enabled="false"

        android:drawable="@drawable/btn_default_normal_disable" />

    <item android:state_pressed="true"

        android:drawable="@drawable/btn_default_pressed" />

    <item android:state_focused="true" android:state_enabled="true"

        android:drawable="@drawable/btn_default_selected" />

    <item android:state_enabled="true"

        android:drawable="@drawable/btn_default_normal" />

    <item android:state_focused="true"

        android:drawable="@drawable/btn_default_normal_disable_focused" />

    <item

         android:drawable="@drawable/btn_default_normal_disable" />

</selector>

 定义了Button各种状态下用到的图片。所以如果我们想自定义一个Button的样式的话我们只需要仿着这个文件来写Button的样式就行了。

0 0
原创粉丝点击