按钮和复选框控件
概述
本篇文章介紹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.
每個狀態(tài)改變時,狀態(tài)列表遍歷從上到下,第一項相匹配的當前狀態(tài)是使用選擇不是基于“最佳匹配”,但只是第一項滿足最低標準的狀態(tài),即:系統(tǒng)是從上往下匹配的,如果匹配到一個item那么它就將采用這個item,而不是采用的最佳匹配的規(guī)則,所以設置缺省的狀態(tài),一定要寫在最后,很多人為了保險起見,一開始就把缺省的寫好,那么這樣后面所有的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"] ><itemandroid: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:
| android:constantSize | 我們在后面那個item里面設置drawable這個東西的大小是不是固定的。我們這個文件一般都是用作控件的Backgroup或者selector總之就是背景狀態(tài),一般背景都是把控件的后面全部覆蓋,但有的時候我們要設置設固定的大小,比如一個Button有300*200大,而設置這個Button的背景圖片只有200*100,而現(xiàn)在我們又不想圖片被拉大把覆蓋整個Button的底層,那么就可以把這個屬性設置為true,這樣圖片就只顯示在中間了,就像我們設置桌面背景一樣,可以設置成居中、拉伸,如果這里設置成true就相當于居中,如果不設置或者設置為false就是拉伸. |
| android:dither | 是否讓系統(tǒng)來幫我們處理顏色差異,一般android系統(tǒng)中使用的顏色是ARGB_8888,但很多顯示設置是RGB_565,這個ARGB_8888與RGB_565有什么區(qū)別呢。這個ARGB_8888也就是說每一個像素點要拿4個字節(jié)來保存,依次每個字節(jié)是A8個字節(jié),R8個字節(jié),G8個字節(jié),B8個字節(jié),來保存,而RGB_565它只用了兩個字節(jié)來保存顏色,兩個字節(jié)總共16位,前5位保存R,中間6位保存G,后5位保存B.因此呀,如果android系統(tǒng)的點顯示到屏幕上,還得轉換一下,在這里這個dither就起作用了,如果我們把它設置為true的話,那顯示的時候屏幕間斷的取點,這樣的結果,有的時候看上去就有那種分層的感覺,也就是前面一部分的顏色與后面一部分的顏色感覺斷層了,就是很不平滑的感覺,如果我們這里設置為true的話,默認就是true,android系統(tǒng),它會在取的點之間再經(jīng)過一些計算,在其間補充一點相間的顏色使看起來比較平滑,但這樣和真的圖片還是有差異的,因些有的人想要得到很逼真的顯示,這里就得自己來計算了,自己來計算,即占內(nèi)存又占cpu,但顏色可以很逼真,如果有這樣的需求那這里就要把這個屬性設置為false |
| android:variablePadding | 可變的填充,在當當前這個組件被selected的時候,比如某一個tab被selected,或者listView里面的個item被selected的時候,如果設置為true的話,那么被選的這個tab或item的填充就會變大,使得看上去與其它的tab或item不一樣。 |
| android:drawable | 如果系統(tǒng)匹配上當前這個item(也就是要使用這個item),那么就用這里設置的資源這個資源,一般都為圖片。 |
| android:state_enabled | 設置觸摸或點擊事件是否可用狀態(tài),一般只在false時設置該屬性,表示不可用狀態(tài)。這個是當一個組件是否能處理touch或click事件的時候的狀態(tài),如果要對組件能否響應事件設置不同背景的時候,就要靠這個屬性了. |
| android:state_pressed | 設置是否按壓狀態(tài),一般在true時設置該屬性,表示已按壓狀態(tài),默認為false。就是說當前這個組件是否被按下,如果要設置按下的那一刻的狀態(tài),那么這里就要設置為true,例如,一個Button當手按下去后,還沒有離開的狀態(tài)(就是touched住的時候,還沒有放開,和Clicked,點擊時的那一刻) |
| android:state_selected | 設置是否選中狀態(tài),true表示已選中,false表示未選中。這個是當一個tab被打開的狀態(tài)。或者一個listView等里面一個item被選擇的時候的狀態(tài),因此這個屬性設置在一般的組件上面是沒有用的,只有設置有作為tab或item的布局里面的項時,這個屬才起作用. |
| android:state_checked | 置是否勾選狀態(tài),主要用于CheckBox和RadioButton,true表示已被勾選,false表示未被勾選 。這個是當一個組件被checked 或者沒有checked 的時候的狀態(tài),也就是說只有在可checkable上面的組件才有作用的,一般常見的就是多選按鈕組與單選按鈕組里面的項,這個才有作用的。 |
| android:state_checkable | 設置勾選是否可用狀態(tài),類似state_enabled,只是state_enabled會影響觸摸或點擊事件,而state_checkable影響勾選事件。這個是當一個組件在可以checked或不可以checked的時候的狀態(tài),現(xiàn)在較常見的,能夠checkable的組件有,單選項和多選項,所以這個屬性只有設置在像這類組件上面才有作用的。 |
| android:state_focused | 設置是否獲得焦點狀態(tài),true表示獲得焦點,默認為false,表示未獲得焦點。 這個是當獲得焦點的時候的狀態(tài),就是當控件高亮的時候的狀態(tài),哪些情況可以造成此狀態(tài)呢,比如說,軌跡球(有的手機上面有一個小球,可以用手指在上面向不同的方向滾動,滾動的時候,界面里面的焦點,就會轉向滾動的方向的控件),還有就是d-pad之類的東西(比如果游戲手柄上面的上下左右鍵,還有鍵盤上面的上下左右鍵等)這些東西就可以控制組件上面的焦點。 |
| android:state_window_focused | 設置當前窗口是否獲得焦點狀態(tài),true表示獲得焦點,false表示未獲得焦點,例如拉下通知欄或彈出對話框時,當前界面就會失去焦點;另外,ListView的ListItem獲得焦點時也會觸發(fā)true狀態(tài),可以理解為當前窗口就是ListItem本身。這個是是否對當前界面是否得到焦點的兩種狀態(tài)的設置,比如說當我們打開一個界面,那么這個界面就獲得了焦點,如果我們?nèi)グ选巴ㄖ崩聛?#xff0c;那么這個界面就失去焦點,或者彈出了一個對話框,那么這個界面也失去焦點了。 |
| android:state_activated | 設置是否被激活狀態(tài),true表示被激活,false表示未激活,API Level 11及以上才支持,可通過代碼調(diào)用控件的setActivated(boolean)方法設置是否激活該控件 |
| android:state_hovered | 設置是否鼠標在上面滑動的狀態(tài),true表示鼠標在上面滑動,默認為false,API Level 14及以上才支持。當光標移動到某一個組件之上的時候的狀態(tài),到目前為止,還沒有看見過哪個手機設備帶有鼠標之類的東西,可能這個專門是為平板電腦設置的或者以后可能出現(xiàn)帶有鼠標之類的設備而準備的吧,文檔中說,一般這個值設置為與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" />圖文混排的按鈕
實現(xiàn)方式
兩種方式:
1. 使用`<Button>`標簽的android:drawableXXX屬性,其中XXX表示Top、Bottom、Left、Right。這4個屬性都是資源類型,需要指定圖像資源的ID,分別表示在上下左右插入一個圖像。同時還可以配合android:drawablePadding屬性來設置圖像到文字的舉例。2. Button和EditText一樣,也是TextView的之類,因此也可以采用與TextView、EditText同樣的方式實現(xiàn)圖文混排(我寫的這個demo在2.3的SDK中運行OK。4.0+以上報錯,未找到原因)android:drawableXXX屬性實現(xiàn)
<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" />代碼實現(xiàn)
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或者其他類似的方法,
<ImageButtonandroid: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 clickedswitch(view.getId()) {case R.id.radio_pirates:if (checked)// Pirates are the bestbreak;case R.id.radio_ninjas:if (checked)// Ninjas rulebreak;} }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 clickedswitch(view.getId()) {case R.id.checkbox_meat:if (checked)// Put some meat on the sandwichelse// Remove the meatbreak;case R.id.checkbox_cheese:if (checked)// Cheese meelse// I'm lactose intolerantbreak;// 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.
總結
- 上一篇: Permission is only g
- 下一篇: 跨进程访问(AIDL服务)