1.創建3種類型的 Button :
1>只有文字的,用 Button 類,如:
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_text" ... />
2>帶有圖片的,用 ImageButton 類,如:
3>有圖片又有文字的,用 Button 類用 android:drawableLeft 屬性:<ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/button_icon" ... />
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_text" android:drawableLeft="@drawable/button_icon" ... />
2.處理單擊事件:
方法1>在xml文件中添加 android:onClick 屬性,其值爲處理該事件的方法名。然後在對應的Activity中實現該方法。如:
在xml中添加 Button,
<?xml version="1.0" encoding="utf-8"?> <Button xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/button_send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" android:onClick="sendMessage" />
然後在對應的 Activity 中實現:
/** Called when the user touches the button */ public void sendMessage(View view) { // Do something in response to button click }
方法2>使用 OnClickListener :
當運行過程中實例化 Button或者需要在 Fragment 子類中聲明點擊行爲的時候,需要用到 OnClickListener。
要使用OnClickListener,先創建一個View.OnClickListener類,然後調用setOnClickListener方法將其分配給 button。如:
Button button = (Button) findViewById(R.id.button_send); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Do something in response to button click } });
3.Button樣式:
1>可以在<application>中聲明主題,如:android:theme="@android:style/Theme.Holo"
2>用 android:background 來定製Button的背景。
3>沒有邊框的Button:
style="?android:attr/borderlessButtonStyle"
4>自定義背景:在xml文件中爲圖片背景創建一個包含3種狀態的狀態列表:
①製作分別代表默認,按下,獲得焦點3種狀態的位圖。爲保證適合不同尺寸,最好做成Nine-patch圖片
②將位圖放置在當前項目的 res/drawable/ 目錄下
③在 res/drawable/ 目錄下新建一個xml文件,如 button_custom.xml:
item的順序有關,例如上方的代碼中,只有當press和focuse都爲false時才輪到default<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/button_pressed" android:state_pressed="true" /> <item android:drawable="@drawable/button_focused" android:state_focused="true" /> <item android:drawable="@drawable/button_default" /> </selector>
④將該xml文件添加到該 Button 的 android:background 屬性中:
android:background="@drawable/button_custom"