概述
本篇文章介绍Android SDK中的按钮和复选框控件。按钮可以分为多种,例如普通按钮(Button)、图像按钮(ImageButton)、选项按钮(RadioButton)、复选框(CheckBox)等
Button
Class Overview
Represents a push-button widget. Push-buttons can be pressed, or clicked, by the user to perform an action.
A typical use of a push-button in an activity would be the following:
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:
<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:
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.
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.
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.
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:
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.
<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.