android Button源码分析
在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的樣式就行了。
總結
以上是生活随笔為你收集整理的android Button源码分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 自定义控件例如LinearLayout
- 下一篇: android分析windowManag