Button和ImageButton的使用

本人平時做項目時,這兩個控件使用的較少,一般都用TextView代替,這裏重新學習下他們的用法。

參考文章 :http://www.runoob.com/w3cnote/android-tutorial-button-imagebutton.html

1.點擊變色效果

StateListDrawable是Drawable資源的一種,可以根據不同的狀態,設置不同的圖片效果,關鍵節點 < selecotr >,我們只需要講Button的blackground屬性設置爲該drawable資源即可輕鬆實現,按下 按鈕時不同的按鈕顏色或背景!

我們可以設置的屬性:
drawable:引用的Drawable位圖,我們可以把他放到最前面,就表示組件的正常狀態~
state_focused:是否獲得焦點
state_window_focused:是否獲得窗口焦點
state_enabled:控件是否可用
state_checkable:控件可否被勾選,eg:checkbox
state_checked:控件是否被勾選
state_selected:控件是否被選擇,針對有滾輪的情況
state_pressed:控件是否被按下
state_active:控件是否處於活動狀態,eg:slidingTab
state_single:控件包含多個子控件時,確定是否只顯示一個子控件
state_first:控件包含多個子控件時,確定第一個子控件是否處於顯示狀態
state_middle:控件包含多個子控件時,確定中間一個子控件是否處於顯示狀態
state_last:控件包含多個子控件時,確定最後一個子控件是否處於顯示狀態

代碼實現:
1)先準備兩種不同顏色的背景,這裏也用drawable實現,用圖片也行。

按下後的背景 文件名: round_stroke_shape_background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <corners android:radius="5dp" />
    <solid android:color="#0dbfc6"/>

</shape>
默認的背景 文件名:round_stroke_shape_background_default.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <corners android:radius="5dp" />
    <solid android:color="#ffffff"/>

</shape>

2)用StateListDrawable資源設置按下效果

文件名:myselect.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:state_pressed="true" android:drawable="@drawable/round_stroke_shape_background"></item>
    <item android:state_enabled="false" android:drawable="@drawable/round_stroke_shape_background_default"></item>
    <item android:drawable="@drawable/round_stroke_shape_background_default"></item>
</selector>

3)將myselect.xml設置爲Button的背景

 <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:background="@drawable/myselect"
        android:padding="15dp"
        android:text="點我變色"
        android:textSize="16sp" />

效果圖如下:
這裏寫圖片描述
這裏寫圖片描述

2.按鈕按下的波紋效果
待續,直接給demo
http://download.csdn.net/detail/kinglong68/9468962 eclipse

http://download.csdn.net/detail/kinglong68/9468950 studio

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章