按鈕和複選框控件

概述

本篇文章介紹Android SDK中的按鈕和複選框控件。按鈕能夠分爲多種,例如普通按鈕(Button)、圖像按鈕(ImageButton)、選項按鈕(RadioButton)、複選框(CheckBox)等html


Button

官方介紹java

Class Overview

Button

Represents a push-button widget. Push-buttons can be pressed, or clicked, by the user to perform an action.android

A typical use of a push-button in an activity would be the following:markdown

public class MyActivity extends Activity {
     protected void onCreate(Bundle icicle) {
         super.onCreate(icicle);

         setContentView(R.layout.content_layout_id);

         final Button button = (Button) findViewById(R.id.button_id);
         button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 // Perform action on click
             }
         });
     }
 }

However, instead of applying an OnClickListener to the button in your activity, you can assign a method to your button in the XML layout, using the android:onClick attribute. For example:app

<Button  android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/self_destruct" android:onClick="selfDestruct" />

Now, when a user clicks the button, the Android system calls the activity’s selfDestruct(View) method. In order for this to work, the method must be public and accept a View as its only parameter. For example:ide

public void selfDestruct(View view) {
     // Kabloey
 }

The View passed into the method is a reference to the widget that was clicked.佈局

Button Style

Every Button is styled using the system’s default button background, which is often different from one device to another and from one version of the platform to another.ui

If you’re not satisfied with the default button style and want to customize it to match the design of your application, then you can replace the button’s background image with a state list drawable.this

A state list drawable is a drawable resource defined in XML that changes its image based on the current state of the button. Once you’ve defined a state list drawable in XML, you can apply it to your Button with the android:backgroundattribute. For more information and an example, see State List Drawable.spa

State List

A StateListDrawable is a drawable object defined in XML that uses a several different images to represent the same graphic, depending on the state of the object. For example, a Button widget can exist in one of several different states (pressed, focused, or neither) and, using a state list drawable, you can provide a different background image for each state.

You can describe the state list in an XML file. Each graphic is represented by an <item> element inside a single <selector> element. Each <item> uses various attributes to describe the state in which it should be used as the graphic for the drawable.

During each state change, the state list is traversed top to bottom and the first item that matches the current state is used—the selection is not based on the 「best match,」 but simply the first item that meets the minimum criteria of the state.
每一個狀態改變時,狀態列表遍歷從上到下,第一項相匹配的當前狀態是使用選擇不是基於「最佳匹配」,但只是第一項知足最低標準的狀態,即:系統是從上往下匹配的,若是匹配到一個item那麼它就將採用這個item,而不是採用的最佳匹配的規則,因此設置缺省的狀態,必定要寫在最後,不少人爲了保險起見,一開始就把缺省的寫好,那麼這樣後面全部的item就都不會起做用了,還會所以找不着哪裏出了問題。

FILE LOCATION:

res/drawable/filename.xml
The filename is used as the resource ID.

COMPILED RESOURCE DATATYPE:

Resource pointer to a StateListDrawable.

RESOURCE REFERENCE:

In Java: R.drawable.filename
In XML: @[package:]drawable/filename

SYNTAX:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:constantSize=["true" | "false"]
    android:dither=["true" | "false"]
    android:variablePadding=["true" | "false"] >
    <item
        android:drawable="@[package:]drawable/drawable_resource"
        android:state_pressed=["true" | "false"]
        android:state_focused=["true" | "false"]
        android:state_hovered=["true" | "false"]
        android:state_selected=["true" | "false"]
        android:state_checkable=["true" | "false"]
        android:state_checked=["true" | "false"]
        android:state_enabled=["true" | "false"]
        android:state_activated=["true" | "false"]
        android:state_window_focused=["true" | "false"] />
</selector>

ELEMENTS:

selector屬性 selector說明
android:constantSize 咱們在後面那個item裏面設置drawable這個東西的大小是否是固定的。咱們這個文件通常都是用做控件的Backgroup或者selector總之就是背景狀態,通常背景都是把控件的後面所有覆蓋,但有的時候咱們要設置設固定的大小,好比一個Button有300*200大,而設置這個Button的背景圖片只有200*100,而如今咱們又不想圖片被拉大把覆蓋整個Button的底層,那麼就能夠把這個屬性設置爲true,這樣圖片就只顯示在中間了,就像咱們設置桌面背景同樣,能夠設置成居中、拉伸,若是這裏設置成true就至關於居中,若是不設置或者設置爲false就是拉伸.
android:dither 是否讓系統來幫咱們處理顏色差別,通常android系統中使用的顏色是ARGB_8888,但不少顯示設置是RGB_565,這個ARGB_8888與RGB_565有什麼區別呢。這個ARGB_8888也就是說每個像素點要拿4個字節來保存,依次每一個字節是A8個字節,R8個字節,G8個字節,B8個字節,來保存,而RGB_565它只用了兩個字節來保存顏色,兩個字節總共16位,前5位保存R,中間6位保存G,後5位保存B.所以呀,若是android系統的點顯示到屏幕上,還得轉換一下,在這裏這個dither就起做用了,若是咱們把它設置爲true的話,那顯示的時候屏幕間斷的取點,這樣的結果,有的時候看上去就有那種分層的感受,也就是前面一部分的顏色與後面一部分的顏色感受斷層了,就是很不平滑的感受,若是咱們這裏設置爲true的話,默認就是true,android系統,它會在取的點之間再通過一些計算,在其間補充一點相間的顏色使看起來比較平滑,但這樣和真的圖片仍是有差別的,因些有的人想要獲得很逼真的顯示,這裏就得本身來計算了,本身來計算,即佔內存又佔cpu,但顏色能夠很逼真,若是有這樣的需求那這裏就要把這個屬性設置爲false
android:variablePadding 可變的填充,在噹噹前這個組件被selected的時候,好比某一個tab被selected,或者listView裏面的個item被selected的時候,若是設置爲true的話,那麼被選的這個tab或item的填充就會變大,使得看上去與其它的tab或item不同。

item屬性 item說明
android:drawable 若是系統匹配上當前這個item(也就是要使用這個item),那麼就用這裏設置的資源這個資源,通常都爲圖片。
android:state_enabled 設置觸摸或點擊事件是否可用狀態,通常只在false時設置該屬性,表示不可用狀態。這個是當一個組件是否能處理touch或click事件的時候的狀態,若是要對組件可否響應事件設置不一樣背景的時候,就要靠這個屬性了.
android:state_pressed 設置是否按壓狀態,通常在true時設置該屬性,表示已按壓狀態,默認爲false。就是說當前這個組件是否被按下,若是要設置按下的那一刻的狀態,那麼這裏就要設置爲true,例如,一個Button當手按下去後,尚未離開的狀態(就是touched住的時候,尚未放開,和Clicked,點擊時的那一刻)
android:state_selected 設置是否選中狀態,true表示已選中,false表示未選中。這個是當一個tab被打開的狀態。或者一個listView等裏面一個item被選擇的時候的狀態,所以這個屬性設置在通常的組件上面是沒有用的,只有設置有做爲tab或item的佈局裏面的項時,這個屬才起做用.
android:state_checked 置是否勾選狀態,主要用於CheckBox和RadioButton,true表示已被勾選,false表示未被勾選 。這個是當一個組件被checked 或者沒有checked 的時候的狀態,也就是說只有在可checkable上面的組件纔有做用的,通常常見的就是多選按鈕組與單選按鈕組裏面的項,這個纔有做用的。
android:state_checkable 設置勾選是否可用狀態,相似state_enabled,只是state_enabled會影響觸摸或點擊事件,而state_checkable影響勾選事件。這個是當一個組件在能夠checked或不能夠checked的時候的狀態,如今較常見的,可以checkable的組件有,單選項和多選項,因此這個屬性只有設置在像這類組件上面纔有做用的。
android:state_focused 設置是否得到焦點狀態,true表示得到焦點,默認爲false,表示未得到焦點。 這個是當得到焦點的時候的狀態,就是當控件高亮的時候的狀態,哪些狀況能夠形成此狀態呢,好比說,軌跡球(有的手機上面有一個小球,能夠用手指在上面向不一樣的方向滾動,滾動的時候,界面裏面的焦點,就會轉向滾動的方向的控件),還有就是d-pad之類的東西(好比果遊戲手柄上面的上下左右鍵,還有鍵盤上面的上下左右鍵等)這些東西就能夠控制組件上面的焦點。
android:state_window_focused 設置當前窗口是否得到焦點狀態,true表示得到焦點,false表示未得到焦點,例如拉下通知欄或彈出對話框時,當前界面就會失去焦點;另外,ListView的ListItem得到焦點時也會觸發true狀態,能夠理解爲當前窗口就是ListItem自己。這個是是否對當前界面是否獲得焦點的兩種狀態的設置,好比說當咱們打開一個界面,那麼這個界面就得到了焦點,若是咱們去把「通知」拉下來,那麼這個界面就失去焦點,或者彈出了一個對話框,那麼這個界面也失去焦點了。
android:state_activated 設置是否被激活狀態,true表示被激活,false表示未激活,API Level 11及以上才支持,可經過代碼調用控件的setActivated(boolean)方法設置是否激活該控件
android:state_hovered 設置是否鼠標在上面滑動的狀態,true表示鼠標在上面滑動,默認爲false,API Level 14及以上才支持。當光標移動到某一個組件之上的時候的狀態,到目前爲止,尚未看見過哪一個手機設備帶有鼠標之類的東西,可能這個專門是爲平板電腦設置的或者之後可能出現帶有鼠標之類的設備而準備的吧,文檔中說,通常這個值設置爲與focused這個值同樣。

EXAMPLE:

XML file saved at res/drawable/button.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/button_pressed" /> <!-- pressed -->
    <item android:state_focused="true" android:drawable="@drawable/button_focused" /> <!-- focused -->
    <item android:state_hovered="true" android:drawable="@drawable/button_focused" /> <!-- hovered -->
    <item android:drawable="@drawable/button_normal" /> <!-- default -->
</selector>

This layout XML applies the state list drawable to a Button:

<Button  android:layout_height="wrap_content" android:layout_width="wrap_content" android:background="@drawable/button" />

圖文混排的按鈕

實現方式

兩種方式:

1. 使用`<Button>`標籤的android:drawableXXX屬性,其中XXX表示Top、Bottom、Left、Right。這4個屬性都是資源類型,須要指定圖像資源的ID,分別表示在上下左右插入一個圖像。同時還能夠配合android:drawablePadding屬性來設置圖像到文字的舉例。
 2. Button和EditText同樣,也是TextView的之類,所以也能夠採用與TextView、EditText一樣的方式實現圖文混排(我寫的這個demo在2.3的SDK中運行OK。4.0+以上報錯,未找到緣由)

android:drawableXXX屬性實現

<Button  android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableTop="@drawable/flag_mark_violet" android:text="按鈕1" />

        <Button  android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableBottom="@drawable/flag_mark_yellow" android:drawablePadding="30dp" android:text="按鈕2" />

        <Button  android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableLeft="@drawable/flag_mark_blue" android:text="按鈕3" />

        <Button  android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawablePadding="20dp" android:drawableRight="@drawable/flag_mark_red" android:text="按鈕4" />

代碼實現

Button button = (Button) findViewById(R.id.button);
        // 左側圖片
        SpannableString spannableStringLeft = new SpannableString("left");
        Bitmap bitmapLeft = BitmapFactory.decodeResource(getResources(),R.drawable.flag_mark_blue);
        ImageSpan imageSpanLeft = new ImageSpan(this,bitmapLeft,DynamicDrawableSpan.ALIGN_BOTTOM);
        spannableStringLeft.setSpan(imageSpanLeft, 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 右側圖片
        SpannableString spannableStringRight = new SpannableString("right");
        Bitmap bitmapRight = BitmapFactory.decodeResource(getResources(),R.drawable.flag_mark_green);
        ImageSpan imageSpanRight = new ImageSpan(this,bitmapRight,DynamicDrawableSpan.ALIGN_BOTTOM);
        spannableStringRight.setSpan(imageSpanRight, 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        button.append(spannableStringLeft);
        button.append("個人按鈕");
        button.append(spannableStringRight);

ImageButton

ImageButton extends ImageView

Displays a button with an image (instead of text) that can be pressed or clicked by the user. By default, an ImageButton looks like a regular Button, with the standard button background that changes color during different button states. The image on the surface of the button is defined either by the android:src attribute in the XML element or by the setImageResource(int) method.

To remove the standard button background image, define your own background image or set the background color to be transparent.

ImageButton能夠做爲圖像按鈕使用,若是想在代碼中修改ImageButton的圖像可使用ImageButton類的setImageResource或者其餘相似的方法,

<ImageButton
        android:id="@+id/id_imgBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@android:color/transparent"
        android:src="@drawable/flag_mark_green"/>

值的注意的是: ImageButton並非TextView的之類,而是ImageView的之類,所以並無android:text屬性,若是要想在ImageButton上添加文字,能夠自定義控件,重寫onDraw方法。


RadioButton

Radio buttons allow the user to select one option from a set. You should use radio buttons for optional sets that are mutually exclusive if you think that the user needs to see all available options side-by-side. If it’s not necessary to show all options side-by-side, use a spinner instead.
這裏寫圖片描述

To create each radio button option, create a RadioButton in your layout. However, because radio buttons are mutually exclusive, you must group them together inside a RadioGroup. By grouping them together, the system ensures that only one radio button can be selected at a time.

Responding to Click Events

When the user selects one of the radio buttons, the corresponding RadioButton object receives an on-click event.

To define the click event handler for a button, add the android:onClick attribute to the element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.

For example, here are a couple RadioButton objects:

<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical">
    <RadioButton android:id="@+id/radio_pirates" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/pirates" android:onClick="onRadioButtonClicked"/>
    <RadioButton android:id="@+id/radio_ninjas" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/ninjas" android:onClick="onRadioButtonClicked"/>
</RadioGroup>

Note: The RadioGroup is a subclass of LinearLayout that has a vertical orientation by default.

Within the Activity that hosts this layout, the following method handles the click event for both radio buttons:

public void onRadioButtonClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();

    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.radio_pirates:
            if (checked)
                // Pirates are the best
            break;
        case R.id.radio_ninjas:
            if (checked)
                // Ninjas rule
            break;
    }
}

The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:

  • Be public
  • Return void
  • Define a View as its only parameter (this will be the View that was clicked)

  • Tip: If you need to change the radio button state yourself (such as when loading a saved CheckBoxPreference), use the setChecked(boolean) or toggle() method.

ToogleButton

官方文檔

A toggle button allows the user to change a setting between two states.

You can add a basic toggle button to your layout with the ToggleButton object. Android 4.0 (API level 14) introduces another kind of toggle button called a switch that provides a slider control, which you can add with a Switch object.

If you need to change a button’s state yourself, you can use the CompoundButton.setChecked() or CompoundButton.toggle() methods.

ToogleButtons

<ToggleButton  android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOn="開" android:textOff="關"/>

Responding to Button Presses

To detect when the user activates the button or switch, create an CompoundButton.OnCheckedChangeListener object and assign it to the button by calling setOnCheckedChangeListener(). For example:

ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // The toggle is enabled
        } else {
            // The toggle is disabled
        }
    }
});

CheckBox

Checkboxes allow the user to select one or more options from a set. Typically, you should present each checkbox option in a vertical list.

這裏寫圖片描述

To create each checkbox option, create a CheckBox in your layout. Because a set of checkbox options allows the user to select multiple items, each checkbox is managed separately and you must register a click listener for each one.

Responding to Click Events

When the user selects a checkbox, the CheckBox object receives an on-click event.

To define the click event handler for a checkbox, add the android:onClick attribute to the element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.

For example, here are a couple CheckBox objects in a list:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
    <CheckBox android:id="@+id/checkbox_meat" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/meat" android:onClick="onCheckboxClicked"/>
    <CheckBox android:id="@+id/checkbox_cheese" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/cheese" android:onClick="onCheckboxClicked"/>
</LinearLayout>

Within the Activity that hosts this layout, the following method handles the click event for both checkboxes:

public void onCheckboxClicked(View view) {
    // Is the view now checked?
    boolean checked = ((CheckBox) view).isChecked();

    // Check which checkbox was clicked
    switch(view.getId()) {
        case R.id.checkbox_meat:
            if (checked)
                // Put some meat on the sandwich
            else
                // Remove the meat
            break;
        case R.id.checkbox_cheese:
            if (checked)
                // Cheese me
            else
                // I'm lactose intolerant
            break;
        // TODO: Veggie sandwich
    }
}

The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:

  • Be public
  • Return void
  • Define a View as its only parameter (this will be the View that was clicked)
  • Tip: If you need to change the radio button state yourself (such as when loading a saved CheckBoxPreference), use the setChecked(boolean) or toggle() method.