Android 中常見控件的介紹和使用


1 TextView文本框

1.1 TextView類的結構

TextView 是用於顯示字符串的組件,對於用戶來說就是屏幕中一塊用於顯示文本的區域。TextView類的層次關系如下:

java.lang.Object

    ↳ android.view.View

    ↳ android.widget.TextView

直接子類:

  Button, CheckedTextView, Chronometer, DigitalClock, EditText

間接子類:

  AutoCompleteTextView, CheckBox, CompoundButton, ExtractEditText,MultiAutoCompleteTextView, RadioButton, ToggleButton

1.2 TextView類的方法

主要方法

功能描述

返回值

TextView

TextView的構造方法

Null

getDefaultMovementmethod

獲取默認的箭頭按鍵移動方式

Movementmethod

getText

獲得TextView對象的文本

CharSquence

length

獲得TextView中的文本長度

Int

getEditableText

取得文本的可編輯對象,通過 這個對象可對TextView的文本進行操作,如在光標之后插入字符

Void

getCompoundPaddingBottom

返回底部填充物

Int

setCompoundDrawables

設置圖像顯示的位置,在 設置該Drawable資源之前需要調用setBounds(Rect)

Void

setCompoundDrawablesWithIn

trinsicBounds

設置Drawable圖像的顯示位置,但其邊界不變

Void

setPadding

根據位置設置填充物

Void

getAutoLinkMask

返回自動連接的掩碼

Void

setTextColor

設置文本顯示的顏色

Void

setHighlightColor

設置文本選中時顯示的顏色

Void

setShadowLayer

設置文本顯示的陰影顏色

Void

setHintTextColor

設置提示文字的顏色

Void

setLinkTextColor

設置鏈接文字的顏色

Void

setGravity

設置當TextView超出了文本本身時橫向以及垂直對齊

Void

getFreezesText

設置該視圖是否包含整個文本,如果包含則返回真值,否則返回假值

Boolean

 

 

 

 

1.3 TextView標簽的屬性

XML屬性

屬性名稱

描述

android:autoLink

設置是否當文本為URL鏈接/email/電話號碼/map時,文本顯示為可點擊的鏈接。可選值(none/web/email/phone/map/all)

android:autoText

如果設置,將自動執行輸入值的拼寫糾正。此處無效果,在顯示輸入法並輸入的時候起作用。

android:bufferType

指定getText()方式取得的文本類別。選項editable 類似於StringBuilder可追加字符,

也就是說getText后可調用append方法設置文本內容。

android:capitalize

設置英文字母大寫類型。此處無效果,需要彈出輸入法才能看得到,參見EditView此屬性說明。

android:cursorVisible

設定光標為顯示/隱藏,默認顯示。

android:digits

設置允許輸入哪些字符。如“1234567890.+-*/%\n()”

android:drawableBottom

在text的下方輸出一個drawable,如圖片。如果指定一個顏色的話會把text的背景設為該顏色,並且同時和background使用時覆蓋后者。

android:drawableLeft

在text的左邊輸出一個drawable,如圖片。

android:drawablePadding

設置text與drawable(圖片)的間隔,與drawableLeft、drawableRight、drawableTop、drawableBottom一起使用,可設置為負數,單獨使用沒有效果。

android:drawableRight

在text的右邊輸出一個drawable,如圖片。

android:drawableTop

在text的正上方輸出一個drawable,如圖片。

android:editable

設置是否可編輯。這里無效果,參見EditView。

android:editorExtras

設置文本的額外的輸入數據。在EditView再討論。

android:ellipsize

設置當文字過長時,該控件該如何顯示。有如下值設置:”start”—–省略號顯示在開頭;”end”——省略號顯示在結尾;”middle”—-省略號顯示在中間;”marquee” ——以跑馬燈的方式顯示(動畫橫向移動)

android:freezesText

設置保存文本的內容以及光標的位置。

android:gravity

設置文本位置,如設置成“center”,文本將居中顯示。

android:hint

Text為空時顯示的文字提示信息,可通過textColorHint設置提示信息的顏色。比較奇怪的是TextView本來就相當於Label,怎么會不設置Text?!

android:imeOptions

附加功能,設置右下角IME動作與編輯框相關的動作,如actionDone右下角將顯示一個“完成”,而不設置默認是一個回車符號。這個在EditView中再詳細說明,此處無用。

android:imeActionId

設置IME動作ID。在EditView再做說明,

android:imeActionLabel

設置IME動作標簽。在EditView再做說明。

android:includeFontPadding

設置文本是否包含頂部和底部額外空白,默認為true。

android:inputMethod

為文本指定輸入法,需要完全限定名(完整的包名)。例如:com.google.android.inputmethod.pinyin,但是這里報錯找不到。

android:inputType

設置文本的類型,用於幫助輸入法顯示合適的鍵盤類型。在EditView中再詳細說明,這里無效果。

android:linksClickable

設置鏈接是否點擊連接,即使設置了autoLink。

android:marqueeRepeatLimit

在ellipsize指定marquee的情況下,設置重復滾動的次數,當設置為marquee_forever時表示無限次。

android:ems

設置TextView的寬度為N個字符的寬度。這里測試為一個漢字字符寬度,如圖:

android:maxEms

設置TextView的寬度為最長為N個字符的寬度。與ems同時使用時覆蓋ems選項。

android:minEms

設置TextView的寬度為最短為N個字符的寬度。與ems同時使用時覆蓋ems選項。

android:maxLength

限制顯示的文本長度,超出部分不顯示。

android:lines

設置文本的行數,設置兩行就顯示兩行,即使第二行沒有數據。

android:maxLines

設置文本的最大顯示行數,與width或者layout_width結合使用,超出部分自動換行,超出行數將不顯示。

android:minLines

設置文本的最小行數,與lines類似。

android:lineSpacingExtra

設置行間距。

android:lineSpacingMultiplier

設置行間距的倍數。如”1.2”

android:numeric

如果被設置,該TextView有一個數字輸入法。此處無用,設置后唯一效果是TextView有點擊效果,此屬性在EdtiView將詳細說明。

android:password

以小點”.”顯示文本

android:phoneNumber

設置為電話號碼的輸入方式。

android:privateImeOptions

設置輸入法選項,此處無用,在EditText將進一步討論。

android:scrollHorizontally

設置文本超出TextView的寬度的情況下,是否出現橫拉條。

android:selectAllOnFocus

如果文本是可選擇的,讓他獲取焦點而不是將光標移動為文本的開始位置或者末尾位置。TextView中設置后無效果。

android:shadowColor

指定文本陰影的顏色,需要與shadowRadius一起使用。效果:

android:shadowDx

設置陰影橫向坐標開始位置。

android:shadowDy

設置陰影縱向坐標開始位置。

android:shadowRadius

設置陰影的半徑。設置為0.1就變成字體的顏色了,一般設置為3.0的效果比較好。

android:singleLine

設置單行顯示。如果和layout_width一起使用,當文本不能全部顯示時,后面用“…”來表示。如android:text="test_ singleLine " android:singleLine="true" android:layout_width="20dp"將只顯示“t…”。如果不設置singleLine或者設置為false,文本將自動換行

android:text

設置顯示文本.

android:textAppearance

設置文字外觀。如“?android:attr/textAppearanceLargeInverse

”這里引用的是系統自帶的一個外觀,?表示系統是否有這種外觀,否則使用默認的外觀。可設置的值如下:textAppearanceButton/textAppearanceInverse/textAppearanceLarge/textAppearanceLargeInverse/textAppearanceMedium/textAppearanceMediumInverse/textAppearanceSmall/textAppearanceSmallInverse

android:textColor

設置文本顏色

android:textColorHighlight

被選中文字的底色,默認為藍色

android:textColorHint

設置提示信息文字的顏色,默認為灰色。與hint一起使用。

android:textColorLink

文字鏈接的顏色.

android:textScaleX

設置文字之間間隔,默認為1.0f。分別設置0.5f/1.0f/1.5f/2.0f效果如下:

 

android:textSize

設置文字大小,推薦度量單位”sp”,如”15sp”

android:textStyle

設置字形[bold(粗體) 0, italic(斜體) 1, bolditalic(又粗又斜) 2] 可以設置一個或多個,用“|”隔開

android:typeface

設置文本字體,必須是以下常量值之一:normal 0, sans 1, serif 2, monospace(等寬字體) 3]

android:height

設置文本區域的高度,支持度量單位:px(像素)/dp/sp/in/mm(毫米)

android:maxHeight

設置文本區域的最大高度

android:minHeight

設置文本區域的最小高度

android:width

設置文本區域的寬度,支持度量單位:px(像素)/dp/sp/in/mm(毫米)。

android:maxWidth

設置文本區域的最大寬度

android:minWidth

設置文本區域的最小寬度

 

 

1.4 TextView的使用

我們可以在XML布局文件中聲明及設置TextView,也可以在代碼中生成TextView組件。

在xml布局中:

 //顯示超鏈接:

<TextView android:id="@+id/textView0" android:layout_width="fill_parent" android:layout_height="wrap_content"

android:textColor="#FF0000"

android:textSize="18dip" android:background="#FFFFFF" android:text="撥打手機:13888888888"

android:gravity="center_vertical|center_horizontal" android:autoLink="phone" />

 

<TextView android:id="@+id/textView1" android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:textColor="#FF0000"

android:textSize="18dip" android:background="#00FF00"

android:text="Google搜索:http://www.google.com.hk" android:gravity="center_vertical|center_horizontal"

android:autoLink="web" />

 

<TextView android:id="@+id/textView2" android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:textColor="#FF0000"

android:textSize="18dip"

android:background="#FFFF00"

android:text="發送郵件:1007857613@qq.com"

android:gravity="center_vertical|center_horizontal" android:autoLink="email" />

 

//設置文字的滾屏

<TextView android:id="@+id/textView3" android:layout_width="fill_parent"

android:layout_height="20dp" android:textSize="18dip"

android:ellipsize="marquee" android:focusable="true"

android:marqueeRepeatLimit="marquee_forever"

android:focusableInTouchMode="true"

android:scrollHorizontally="true"

android:text="文字滾屏文字跑馬燈效果加長加長加長加長加長加長加長加長加長加長加長加長"

android:background="#FF0000"

android:textColor="#FFFFFF">

   </TextView>

 

//設置字符陰影

<TextView android:id="@+id/TextView4" android:layout_width="fill_parent"

android:layout_height="wrap_content" android:textSize="18dip"

android:background="#69541b" android:textColor="#FFFFFF" android:text="設置字符串陰影顏色為綠色"

android:shadowColor="#45b97c" android:shadowRadius="3.0"

android:gravity="center_vertical|center_horizontal" />

   //設置字符的外形

<TextView android:layout_width="fill_parent"

android:layout_height="wrap_content" android:textSize="18dip"

android:background="#FFFFFF" android:textColor="#FF0000" android:text="設置文字外形為italic"

android:textStyle="italic" android:gravity="center_vertical|center_horizontal" />

 

</LinearLayout>

 

在代碼中:

/動態創建textView

      linearLayout = (LinearLayout)findViewById(R.id.linearLayout01);

      param  = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,

           LinearLayout.LayoutParams.WRAP_CONTENT);

        LinearLayout layout1 = new LinearLayout(this);

      layout1.setOrientation(LinearLayout.HORIZONTAL);

        TextView tv = new TextView(this);

        tv.setId(200);

        tv.setText("動態創建TextView");

        tv.setBackgroundColor(Color.GREEN);

        tv.setTextColor(Color.RED);

        tv.setTextSize(20);

        layout1.addView(tv, param);

        linearLayout.addView(layout1, param);

 

效果圖:

 

 

 

2 EditText編輯框

2.1 EditText類的結構

EditText和TextView的功能基本類似,他們之間的主要區別在於EditText提供了可編輯的文本框。

java.lang.Object

android.view.View

android.widget.TextView        

android.widget.EditText

 

直接子類:

AutoCompleteTextView, ExtractEditText

 

間接子類:

MultiAutoCompleteTextView

 

2.2 EditText常用的方法

方法

功能描述

返回值

setImeOptions

設置軟鍵盤的Enter鍵

void

getImeActionLable

設置IME動作標簽

Charsequence

getDefaultEditable

獲取是否默認可編輯

boolean

setEllipse

設置文件過長時控件的顯示方式

void

setFreeezesText

設置保存文本內容及光標位置

void

getFreeezesText

獲取保存文本內容及光標位置

boolean

setGravity

設置文本框在布局中的位置

void

getGravity

獲取文本框在布局中的位置

int

setHint

設置文本框為空時,文本框默認顯示的 字符

void

getHint

獲取文本框為空時,文本框默認顯示的 字符

Charsequence

setIncludeFontPadding

設置文本框是否包含底部和頂端的額外空白

void

setMarqueeRepeatLimit

在ellipsize指定marquee的情況下,設置重復滾動的次數,

當設置為marquee_forever時表示無限次

void

 

2.3 EditText標簽的主要屬性

屬性名稱

描述

android:autoLink

設置是否當文本為URL鏈接/email/電話號碼/map時,文本顯示為可點擊的鏈接。可選值(none/web/email/phone/map/all)。這里只有在同時設置text時才自動識別鏈接,后來輸入的無法自動識別。

android:autoText

自動拼寫幫助。這里單獨設置是沒有效果的,可能需要其他輸入法輔助才行,效果參見視頻

android:bufferType

指定getText()方式取得的文本類別。選項editable 類似於StringBuilder可追加字符,

也就是說getText后可調用append方法設置文本內容。spannable 則可在給定的字符區域使用樣式,參見這里1這里2

android:capitalize

設置英文字母大寫類型。設置如下值:sentences僅第一個字母大寫;words每一個單詞首字母大小,用空格區分單詞;characters每一個英文字母都大寫。在模擬器上用PC鍵盤直接輸入可以出效果,但是用軟鍵盤無效果。

android:cursorVisible

設定光標為顯示/隱藏,默認顯示。如果設置false,即使選中了也不顯示光標欄。

android:digits

設置允許輸入哪些字符。如“1234567890.+-*/%\n()”

android:drawableTop

在text的正上方輸出一個drawable。在EditView中的效果比較搞笑:,居然在文本框里,而且刪不了。

android:drawableBottom

在text的下方輸出一個drawable(如圖片)。如果指定一個顏色的話會把text的背景設為該顏色,並且同時和background使用時覆蓋后者。

android:drawableLeft

在text的左邊輸出一個drawable(如圖片)。

android:drawablePadding

設置text與drawable(圖片)的間隔,與drawableLeft、drawableRight、drawableTop、drawableBottom一起使用,可設置為負數,單獨使用沒有效果。

android:drawableRight

在text的右邊輸出一個drawable,如圖片。

android:editable

設置是否可編輯。仍然可以獲取光標,但是無法輸入。

android:editorExtras

指定特定輸入法的擴展,如“com.mydomain.im.SOME_FIELD”。源碼跟蹤至EditorInfo.extras,暫無相關實現代碼。

android:ellipsize

設置當文字過長時,該控件該如何顯示。有如下值設置:”start”—–省略號顯示在開頭;”end”——省略號顯示在結尾;”middle”—-省略號顯示在中間;”marquee” ——以跑馬燈的方式顯示(動畫橫向移動)

android:freezesText

設置保存文本的內容以及光標的位置。參見:這里

android:gravity

設置文本位置,如設置成“center”,文本將居中顯示。

android:hint

Text為空時顯示的文字提示信息,可通過textColorHint設置提示信息的顏色。

android:imeOptions

設置軟鍵盤的Enter鍵。有如下值可設置:normal,actionUnspecified,actionNone,actionGo,actionSearch,actionSend,actionNext,actionDone,flagNoExtractUi,flagNoAccessoryAction,flagNoEnterAction。可用’|’設置多個。這里僅設置顯示圖標之用,參見文章末尾例子。

android:imeActionId

設置IME動作ID,在onEditorAction中捕獲判斷進行邏輯操作。

android:imeActionLabel

設置IME動作標簽。但是不能保證一定會使用,猜想在輸入法擴展的時候應該有用。

android:includeFontPadding

設置文本是否包含頂部和底部額外空白,默認為true。

android:inputMethod

為文本指定輸入法,需要完全限定名(完整的包名)。例如:com.google.android.inputmethod.pinyin,但是這里報錯找不到。關於自定義輸入法參見這里

sentences僅第一個字母大寫;words每一個單詞首字母大小,用空格區分單詞;characters每一個英文字母都大寫

android:inputType

設置文本的類型,用於幫助輸入法顯示合適的鍵盤類型。有如下值設置:none、text、textCapCharacters字母大小、textCapWords單詞首字母大小、textCapSentences僅第一個字母大小、textAutoCorrect、textAutoComplete自動完成、textMultiLine多行輸入、textImeMultiLine輸入法多行(如果支持)、textNoSuggestions不提示、textEmailAddress電子郵件地址、textEmailSubject郵件主題、textShortMessage短信息(會多一個表情按鈕出來,點開如下圖:

)、textLongMessage長訊息?、textPersonName人名、textPostalAddress地址、textPassword密碼、textVisiblePassword可見密碼、textWebEditText作為網頁表單的文本、textFilte文本篩選過濾、textPhonetic拼音輸入、numberSigned有符號數字格式、numberDecimal可帶小數點的浮點格式、phone電話號碼、datetime時間日期、date日期、time時間。部分參考這里

android:marqueeRepeatLimit

在ellipsize指定marquee的情況下,設置重復滾動的次數,當設置為marquee_forever時表示無限次。

android:ems

設置TextView的寬度為N個字符的寬度。參見TextView中此屬性的截圖。

android:maxEms

設置TextView的寬度為最長為N個字符的寬度。與ems同時使用時覆蓋ems選項。

android:minEms

設置TextView的寬度為最短為N個字符的寬度。與ems同時使用時覆蓋ems選項。

android:maxLength

限制輸入字符數。如設置為5,那么僅可以輸入5個漢字/數字/英文字母。

android:lines

設置文本的行數,設置兩行就顯示兩行,即使第二行沒有數據。

android:maxLines

設置文本的最大顯示行數,與width或者layout_width結合使用,超出部分自動換行,超出行數將不顯示。

android:minLines

設置文本的最小行數,與lines類似。

android:linksClickable

設置鏈接是否點擊連接,即使設置了autoLink。

android:lineSpacingExtra

設置行間距。

android:lineSpacingMultiplier

設置行間距的倍數。如”1.2”

android:numeric

如果被設置,該TextView有一個數字輸入法。有如下值設置:integer正整數、signed帶符號整數、decimal帶小數點浮點數。

android:password

以小點”.”顯示文本

android:phoneNumber

設置為電話號碼的輸入方式。

android:privateImeOptions

提供額外的輸入法選項(字符串格式)。依據輸入法而決定是否提供,如這里所見。自定義輸入法繼承

InputMethodService。這篇文章也許有幫助。

android:scrollHorizontally

設置文本超出TextView的寬度的情況下,是否出現橫拉條。

android:selectAllOnFocus

如果文本是可選擇的,讓他獲取焦點而不是將光標移動為文本的開始位置或者末尾位置。TextView中設置后無效果。

android:shadowColor

指定文本陰影的顏色,需要與shadowRadius一起使用。參見TextView中此屬性的截圖。

android:shadowDx

設置陰影橫向坐標開始位置。

android:shadowDy

設置陰影縱向坐標開始位置。

android:shadowRadius

設置陰影的半徑。設置為0.1就變成字體的顏色了,一般設置為3.0的效果比較好。

android:singleLine

設置單行顯示。如果和layout_width一起使用,當文本不能全部顯示時,后面用“…”來表示。如android:text="test_ singleLine " android:singleLine="true" android:layout_width="20dp"將只顯示“t…”。如果不設置singleLine或者設置為false,文本將自動換行

android:text

設置顯示文本.

android:textAppearance

設置文字外觀。如“?android:attr/textAppearanceLargeInverse

”這里引用的是系統自帶的一個外觀,?表示系統是否有這種外觀,否則使用默認的外觀。可設置的值如下:textAppearanceButton/textAppearanceInverse/textAppearanceLarge/textAppearanceLargeInverse/textAppearanceMedium/textAppearanceMediumInverse/textAppearanceSmall/textAppearanceSmallInverse

android:textColor

設置文本顏色

android:textColorHighlight

被選中文字的底色,默認為藍色

android:textColorHint

設置提示信息文字的顏色,默認為灰色。與hint一起使用。

android:textColorLink

文字鏈接的顏色.

android:textScaleX

設置文字縮放,默認為1.0f。參見TextView的截圖。

android:textSize

設置文字大小,推薦度量單位”sp”,如”15sp”

android:textStyle

設置字形[bold(粗體) 0, italic(斜體) 1, bolditalic(又粗又斜) 2] 可以設置一個或多個,用“|”隔開

android:typeface

設置文本字體,必須是以下常量值之一:normal 0, sans 1, serif 2, monospace(等寬字體) 3]

android:height

設置文本區域的高度,支持度量單位:px(像素)/dp/sp/in/mm(毫米)

android:maxHeight

設置文本區域的最大高度

android:minHeight

設置文本區域的最小高度

android:width

設置文本區域的寬度,支持度量單位:px(像素)/dp/sp/in/mm(毫米),與layout_width的區別看這里

android:maxWidth

設置文本區域的最大寬度

android:minWidth

設置文本區域的最小寬度

 

2.4 EditText的使用 

EditText和TextView一樣,既可以在Xml中聲明實現,也可以在代碼中動態的生成,關於在代碼動態生成和TextView的類似,這里就不在贅述。下面以一個實例來說明EditText的簡單使用:

 XML布局中:

<TextView android:text="TextView" android:id="@+id/textView1"

      android:layout_height="wrap_content" android:layout_width="fill_parent"></TextView>

 

 <!-- 用於輸入數字的文本框 -->

   <EditText android:id="@+id/editText1" android:inputType="date"

      android:layout_width="fill_parent" android:layout_height="wrap_content"

      android:maxLength="40" android:hint="輸入電話號碼" android:textColorHint="#FF000000"

      android:phoneNumber="true" android:imeOptions="actionGo"></EditText>

 

   <!-- 用於輸入密碼的文本框 -->

   <EditText android:id="@+id/editText2" android:inputType="date"

      android:layout_width="fill_parent" android:layout_height="wrap_content"

      android:maxLength="40" android:hint="輸入密碼" android:textColorHint="#FF000000"

      android:password="true" android:imeOptions="actionSearch"></EditText>

 

/rec/values/string.xml中:

string  name="RadioButton1">Windows</string >

    <string  name="RadioButton2">Linux</string >

    <string  name="RadioButton3">Mocos</string >

    <string  name="RadioButton4">Java</string >

 

Activity中讓editText顯示在屏幕上並實現監聽:

/**

         * 獲得TextView對象

         * 獲得兩個EditTextView對象

         */

        textview = (TextView)findViewById(R.id.textView1);

        edittext_num = (EditText)findViewById(R.id.editText1);

        edittext_pass= (EditText)findViewById(R.id.editText2);

        /**

         * 對EditText進行監聽

         * 獲得編輯框里面的內容並顯示

         */

        edittext_num.addTextChangedListener(new TextWatcher() {

       

        @Override

        public void onTextChanged(CharSequence s, int start, int before, int count) {

          

           //if(!(textview.getText().toString()==null))

              textview.setText("edittext_num:"+edittext_num.getText().toString());

        }

       

        @Override

        public void beforeTextChanged(CharSequence s, int start, int count,

              int after) {

           // TODO Auto-generated method stub

          

        }

       

        public void afterTextChanged(Editable s) {

           // TODO Auto-generated method stub

          

        }

      });

          

        edittext_pass.addTextChangedListener(new TextWatcher() {

       

        @Override

        public void onTextChanged(CharSequence s, int start, int before, int count) {

          

           //if(!(textview.getText().toString()==null))

              textview.setText("你正在編輯edittext_pass");

        }

        public void beforeTextChanged(CharSequence s, int start, int count,

              int after) {

           // TODO Auto-generated method stub

        }

          

        public void afterTextChanged(Editable s) {

           // TODO Auto-generated method stub

        }

      });

}

示例的效果圖如下:

 

 

3 Button按鈕

3.1Button類的結構

Button類的層次關系如下:

java.lang.Object

    ↳ android.view.View

        ↳ android.widget.TextView

             ↳android.widget.Button

 

直接子類:

     CompoundButton

         

間接子類:

CheckBox, RadioButton, ToggleButton

 

3.2 Button類的方法

方法

功能描述

返回值

Button

Button類的構造方法

Null

onKeyDown

當用戶按鍵時,該方法調用

Boolean

onKeyUp

當用戶按鍵彈起后,該方法被調用

Boolean

onKeyLongPress

當用戶保持按鍵時,該方法被調用

Boolean

onKeyMultiple

當用戶多次調用時,該方法被調用

Boolean

invalidateDrawable

刷新Drawable對象

void

scheduleDrawable

定義動畫方案的下一幀

void

unscheduleDrawable

取消scheduleDrawable定義的動畫方案

void

onPreDraw

設置視圖顯示,列如在視圖顯示之前調整滾動軸的邊界

Boolean

sendAccessibilityEvent

發送事件類型指定的AccessibilityEvent。發送請求之前,需要檢查Accessibility是否打開

void

sendAccessibilityEventUnchecked

發送事件類型指定的AccessibilityEvent。發送請求之前,不需要檢查Accessibility是否打開

void

setOnKeyListener

設置按鍵監聽

void

 

3.3 Button標簽的屬性

由於Button是繼承TextView,所以TextView有的屬性,它都能用。

屬性

描述

android:layout_height

設置控件高度。可選值:fill_parent,warp_content,px

android:layout_width

設置控件寬度,可選值:fill_parent,warp_content,px

android:text

設置控件名稱,可以是任意字符

android:layout_gravity

設置控件在布局中的位置,可選項:top,left,bottom,right,center_vertical,fill_vertica,fill_horizonal,center,fill等

android:layout_weight

設置控件在布局中的比重,可選值:任意的數字

android:textColor

設置文字的顏色

android:bufferType

設置取得的文本類別,normal、spannable、editable

android:hint

設置文本為空是所顯示的字符

android:textColorHighlight

設置文本被選中時,高亮顯示的顏色

android:inputType

設置文本的類型,none,text,textWords等

 

3.4 Button的使用

Button可以在xml中聲明,也可以在代碼中動態創建。

在xml中:

<Button android:orientation="vertical" 

       android:layout_height="wrap_content"  android:id="@+id/button1"

       android:layout_width="wrap_content"

       android:textColor="#0000FF"

       android:text="這是button1,可以點擊" />

       <Button android:orientation="vertical" 

       android:layout_height="wrap_content"  android:id="@+id/button2"

       android:layout_width="wrap_content"

       android:textColor="#CD0000"

       android:text="這是button2,可以點擊" />

       <Button android:orientation="vertical" 

       android:layout_height="wrap_content"  android:id="@+id/button3"

       android:layout_width="wrap_content"

      android:textColor="#000000"

       android:text="這是button3,可以點擊" />

 

 

在代碼中創建Button:

button4 = new Button(this);

        button4.setId(100);

        button4.setText("動態創建的Button");

        button4.setTextColor(Color.GREEN);

 

創建好了Button后,我們就可以對其進行監聽了,其中有兩種方式:

一種是繼承OnClickListenner接口:

public class ButtonActivity extends Activity implements OnClickListener{

button1 = (Button)findViewById(R.id.button1);

button1.setOnClickListener(this);

public void onClick(View v) {

  switch(v.getId()){

      case R.id.button1:

       .........

      break;

}

}

}

另一種方式是:

public class ButtonActivity extends Activity{

  button1 = (Button)findViewById(R.id.button1);

button1.setOnClickListener(new Button.OnClickListener(){

 

      public void onClick(View v) {

        // TODO Auto-generated method stub

        ..........

      }

         

       });

 

 

 

 

效果圖:

 

 

4 ImageButton圖片按鈕

4.1 ImageButton類的結構

ImageButton是帶有圖標的按鈕,它的類層次關系如下:

java.lang.Object

android.view.View

android.widget.ImageView

android.widget.ImageButton

4.1 ImageButton類常用的方法

方法

功能描述

返回值

ImageButton

構造函數

null

setAdjustViewBounds

設置是否保持高寬比,需要與maxWidth和maxHeight結合起來一起使用

Boolean

getDrawable

獲取Drawable對象,獲取成功返回Drawable,否則返回null

Drawable

getScaleType

獲取視圖的填充方式

ScaleType

setScaleType

設置視圖的填充方式,包括矩陣、拉伸等七種填充方式

void

setAlpha

設置圖片的透明度

void

setMaxHeight

設置按鈕的最大高度

void

setMaxWidth

設置按鈕的最大寬度

void

setImageURI

設置圖片的地址

void

setImageResource

設置圖片資源庫

void

setOnTouchListener

設置事件的監聽

Boolean

setColorFilter

設置顏色過濾

void

 

4.2 ImageButton標簽的常用屬性

 

屬性

描述

android:adjustViewBounds

設置是否保持寬高比,true或false

android:cropToPadding

是否截取指定區域用空白代替。單獨設置無效果,需要與scrollY一起使用。True或者false

android:maxHeight

設置圖片按鈕的最大高度

android:maxWidth

設置圖片的最大寬度

android:scaleType

設置圖片的填充方式

android:src

設置圖片按鈕的drawable

android:tint

設置圖片為渲染顏色

 

4.3ImageButton的使用

兩種實現方式,在xml和代碼中都可以實現,但相比較而言,在xml中實現更有利於代碼的改動:

 在xml中聲明 :

<ImageButton

 android:id="@+id/button1"

 android:layout_width="wrap_content"

 android:layout_height="wrap_content"

 android:src="@drawable/p1" //使用自己的圖片

/>

<ImageButton

 android:id="@+id/button2"

 android:layout_width="wrap_content"

 android:layout_height="wrap_content"

 android:src="@android:drawable/sym_call_incoming " //使用系統自帶的圖片

/>

 

在代碼中創建

magebutton3 =  new ImageButton(this);

        imagebutton3.setId(100);

        //設置自己的圖片

  imagebutton3.setBackgroundDrawable(getResources().getDrawable(R.drawable.p2));

 

接下來就可以對imagebutton進行監聽,我們這里是在通過繼承OnClickListener接口來實現的:

 

    imagebutton1 = (ImageButton)findViewById(R.id.button1);

        imagebutton2 = (ImageButton)findViewById(R.id.button2);

        //注冊監聽

        imagebutton1.setOnClickListener(this);

        imagebutton2.setOnClickListener(this);

       /注冊監聽

        imagebutton3.setOnClickListener(this);

        //加入布局

        layout = new LinearLayout(this);

        layout.addView(imagebutton3,param);

        linnearlayout.addView(layout,param);

public void onClick(View v) {

       // TODO Auto-generated method stub

       switch(v.getId()){

       case R.id.button1:

           textveiw.setText("你剛才點擊的是ImageButton1");

           break;

       case R.id.button2:

           textveiw.setText("你剛才點擊的是ImageButton2");

           break;

       case 100:

          

           textveiw.setText("你剛才點擊的是ImageButton3");

           if(s){

       imagebutton3.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.stat_sys_vp_phone_call_on_hold));

            s=false;

            break;

           }

          

           imagebutton3.setBackgroundDrawable(getResources().getDrawable(R.drawable.p2));

           s = true;

          break;

      

       }

    }

效果如下:

 

5 CheckBox多項選擇

5.1 CheckBox類的層次關系

多項選擇CheckBox組件也被稱為復選框,該組件常用於某選項的打開或者關閉。它的層次關系如下:

java.lang.Object

android.view.View

  android.widget.TextView

    android.widget.Button

      android.widget.CompoundButton

        android.widget.CheckBox

 

5.2 CheckBox常用的方法

方法

功能描述

返回值

dispatchPopulateAccessibilityEvent

在子視圖創建時,分派一個輔助事件

boolean(true:完成輔助事件分發 false:沒有完成輔助事件分發)

isChecked

判斷組件狀態是否勾選

boolean(true:被勾選,false:未被勾選)

onRestoreInstanceState

設置視圖恢復以前的狀態

void

performClick

執行click動作,該動作會觸發事件監聽器

boolean(true:調用事件監聽器,false:沒有調用事件監聽器)

setButtonDrawable

根據Drawable對象設置組件的背景

void

setChecked

設置組件的狀態

void

setOnCheckedChangeListener

設置事件監聽器

void

tooggle

改變按鈕當前的狀態

void

onCreateDrawableState

獲取文本框為空時,文本框里面的內容

CharSequence

onCreateDrawableState

為當前視圖生成新的Drawable狀態

int[]

 

5.3 CheckBox的使用

 下面是一個使用ChekBox的實例:

XML中聲明定義4CheckBox

<TextView 

  android:id="@+id/TextView1"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:text="@string/hello"

    />

<CheckBox

  android:id="@+id/CheckBox1"

  android:layout_width="fill_parent"

  android:layout_height="wrap_content"

  android:text="@string/CheckBox1"

</CheckBox>

<CheckBox

  android:id="@+id/CheckBox2"

  android:layout_width="fill_parent"

  android:layout_height="wrap_content"

  android:text="@string/CheckBox2"

</CheckBox>

<CheckBox

android:id="@+id/CheckBox3"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/CheckBox3"

</CheckBox>

<CheckBox

android:id="@+id/CheckBox4"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/CheckBox4"

</CheckBox>

    <Button

      android:id="@+id/button1"

      android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:text="提交"

    >

</Button>

 

/rec/values/string.xml中定義四個選項:

<string name="CheckBox1">籃球</string>

     <string name="CheckBox2">足球</string>

     <string name="CheckBox3">乒乓球</string>

 <string name="CheckBox4">排球</string>

 

然后在Activity中就可以使用並監聽CheckBox了:

 

//用來顯示題目

   TextView m_TextView1;

   //“提交按鈕”

   Button     m_Button1;

   //4個多選項

   CheckBox m_CheckBox1;

   CheckBox m_CheckBox2;

   CheckBox m_CheckBox3;

   CheckBox m_CheckBox4;

  

   /** Called when the activity is first created. */

   @Override

   public void onCreate(Bundle savedInstanceState)

   {

      super.onCreate(savedInstanceState);

      setContentView(R.layout.main);

 

      m_TextView1 = (TextView) findViewById(R.id.TextView1);

      m_Button1 = (Button) findViewById(R.id.button1);

 

      /* 取得每個CheckBox對象 */

      m_CheckBox1 = (CheckBox) findViewById(R.id.CheckBox1);

      m_CheckBox2 = (CheckBox) findViewById(R.id.CheckBox2);

      m_CheckBox3 = (CheckBox) findViewById(R.id.CheckBox3);

      m_CheckBox4 = (CheckBox) findViewById(R.id.CheckBox4);

 

      //對每個選項設置事件監聽

      m_CheckBox1.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {

        @Override

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)

        {

           if(m_CheckBox1.isChecked())

           {

              DisplayToast("你選擇了:"+m_CheckBox1.getText());

           }

        }

      });

      ////////////////////

      m_CheckBox2.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {

        @Override

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)

        {

           if(m_CheckBox2.isChecked())

           {

              DisplayToast("你選擇了:"+m_CheckBox2.getText());

           }

        }

      });

      /////////////////

      m_CheckBox3.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {

        @Override

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)

        {

           if(m_CheckBox3.isChecked())

           {

              DisplayToast("你選擇了:"+m_CheckBox3.getText());

           }

        }

      });

      ////////////////

      m_CheckBox4.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {

        @Override

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)

        {

           if(m_CheckBox4.isChecked())

           {

              DisplayToast("你選擇了:"+m_CheckBox4.getText());

           }

        }

      });

      //對按鈕設置事件監聽

      m_Button1.setOnClickListener(new Button.OnClickListener() {

        public void onClick(View v)

        {

           int num = 0;

           if(m_CheckBox1.isChecked())

           {

              num++;

           }

           if(m_CheckBox2.isChecked())

           {

              num++;

           }

           if(m_CheckBox3.isChecked())

           {

              num++;

           }

           if(m_CheckBox4.isChecked())

           {

              num++;

           }

           DisplayToast("謝謝參與!你一共選擇了"+num+"項!");

        }

      });

   }

  

   /* 顯示Toast  */

   public void DisplayToast(String str)

   {

      Toast toast = Toast.makeText(this, str, Toast.LENGTH_SHORT);

      //設置toast顯示的位置

      toast.setGravity(Gravity.TOP, 0, 220);

      //顯示該Toast

      toast.show();

   }

該實例的運行效果圖如下所示;

 

 

6 RadioGroup、RadioButton單項選擇

6.1類的層次關系

RadioButton指的是一個單選按鈕,它有選中和不選中兩種狀態,而RadioGroup組件也被稱為單項按鈕組,它可以有多個RadioButton。一個單選按鈕組只可以勾選一個按鈕,當選擇一個按鈕時,會取消按鈕組中其他已經勾選的按鈕的選中狀態。

RadioButton的類層次關系如下:

java.lang.Object

android.view.View

       android.widget.TextView

android.widget.Button

android.widget.CompoundButton

android.widget.RadioButton

 

而RadioGroup類的層次關系如下:

java.lang.Object

   android.view.View

     android.view.ViewGroup

        android.widget.LinearLayout                   android.widget.RadioGroup

 

6.2常用的方法

RadioButton使用到的公共方法:

public void toggle ()

         //將單選按鈕更改為與當前選中狀態相反的狀態。

         //如果這個單選按鈕已經選中,這個方法將不切換單選按鈕。

 該方法的源碼如下:

 

 

 

RadioGroup中使用到的公共方法:

 

(1)public void addView (View child, int index, ViewGroup.LayoutParams params)

 功能:使用指定的布局參數添加一個子視圖

參數:child     所要添加的子視圖

index     將要添加子視圖的位置

params     所要添加的子視圖的布局參數

                           

 

(2)public void check (int id) 

   如果傳遞-1作為指定的選擇標識符來清除單選按鈕組的勾選狀態,相當於調用clearCheck()操作

參數:id  該組中所要勾選的單選按鈕的唯一標識符(id)

    參見 getCheckedRadioButtonId()   clearCheck()

                           

(3)public void clearCheck () 

功能:清除當前的選擇狀態,當選擇狀態被清除,則單選按鈕組里面的所有單選按鈕將取消勾選狀態,getCheckedRadioButtonId()將返回null

  參見

     check(int)

     getCheckedRadioButtonId()

 

(4)public RadioGroup.LayoutParams generateLayoutParams (AttributeSet attrs)   

功能:基於提供的屬性集合返回一個新的布局參數集合

參數: attrs 用於生成布局參數的屬性

返回值:返回一個ViewGroup.LayoutParams或其子類的實例                       

                  

(5)public int getCheckedRadioButtonId ()  

功能:返回該單選按鈕組中所選擇的單選按鈕的標識ID,如果沒有勾選則返回-1

  返回值:返回該單選按鈕組中所選擇的單選按鈕的標識ID                

                           

  參見

      check(int)                     

clearCheck()

 

(6)public void setOnCheckedChangeListener (RadioGroup.OnCheckedChangeListener listener)

功能:注冊一個當該單選按鈕組中的單選按鈕勾選狀態發生改變時所要調用的回調函數

參數:listener 當單選按鈕勾選狀態發生改變時所要調用的回調函數

                             

                           

(7)public void setOnHierarchyChangeListener (ViewGroup.OnHierarchyChangeListener listener)

功能:注冊一個當子內容添加到該視圖或者從該視圖中移除時所要調用的回調函數

參數:listener    當層次結構發生改變時所要調用的回調函數

                           

 

RadioGroup中受保護的方法:

(1)protected LinearLayout.LayoutParams generateDefaultLayoutParams ()

功能:當布局為垂直方向時,將返回一個寬度為“填充父元素”(MATCH_PARENT),高度為“包裹內容”的布局參數集合,如果為水平方向時,將返回寬度為“包裹內容”,高度為“填充父元素”的布局參數集合

(match_parent即為fill_parent,public static final int FILL_PARENT/MATCH_PARENT = -1 )

返回值:返回一個默認的布局參數集合

 

(2)protected void onFinishInflate ()

功能:當視圖從XML中加載,且相應的子視圖被添加之后,調用該方法,

即使子類重寫了該方法,應該確保去調用父類的方法(通常放在方法在第一句),這樣才能完成相應的調用參數

 返回值: 返回一個默認的布局參數集合 

              

6.3RadioButton和RadioGroup的綜合使用

  XML布局中

  <RadioGroup

    android:id="@+id/RadioGroup01"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:orientation="vertical"

    android:layout_x="3px"

    android:layout_y="54px"

<!--      選項要在rec/values/string.xml中定義 -->

    <RadioButton

      android:id="@+id/RadioButton1"

      android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:text="@string/RadioButton1"

    />

    <RadioButton

      android:id="@+id/RadioButton2"

      android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:text="@string/RadioButton2"

    />

    <RadioButton

      android:id="@+id/RadioButton3"

      android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:text="@string/RadioButton3"

    />

    <RadioButton

      android:id="@+id/RadioButton4"

      android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:text="@string/RadioButton4"

    />

</RadioGroup>   

 

Avtivity中:

/**

        * 獲得TextView對象

        * 獲得RadioGroup對象

        * 獲得4個RadioButton對象

        */

       m_TextView = (TextView) findViewById(R.id.TextView01);

       m_RadioGroup = (RadioGroup) findViewById(R.id.RadioGroup01);

       m_Radio1 = (RadioButton) findViewById(R.id.RadioButton1);

       m_Radio2 = (RadioButton) findViewById(R.id.RadioButton2);

       m_Radio3 = (RadioButton) findViewById(R.id.RadioButton3);

       m_Radio4 = (RadioButton) findViewById(R.id.RadioButton4);

 

       /* 設置事件監聽  */

       m_RadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

           @Override

           public void onCheckedChanged(RadioGroup group, int checkedId)

           {

              // TODO Auto-generated method stub

              if (checkedId == m_Radio2.getId())

              {

                  DisplayToast("正確答案:" + m_Radio2.getText() + ",恭喜你,回答正確!");

              }

               else

              {

                  DisplayToast("請注意,回答錯誤!");

              }

           }

       });

    }

   

    /* 顯示Toast  */

    public void DisplayToast(String str)

    {

       Toast toast = Toast.makeText(this, str, Toast.LENGTH_LONG);

       //設置toast顯示的位置

       toast.setGravity(Gravity.TOP, 0, 220);

       //顯示該Toast

       toast.show();

    }

示例的效果圖如下:

 

 

 

 

7 Toast提示

7.1 Toast類的結構

Toast是Android提供的“快顯訊息”類,它的用途很多,使用起來非常的簡單。它是直接繼承java.lang.Object的。因此它的類層次結構如下:

 

java.lang.Object

android.widget.Toast

7.2 Toast的常量

Toast中有兩個關於Toast顯示時間長短的常量:

常量

         int   LENGTH_LONG      

持續顯示視圖或文本提示較長時間。該時間長度可定制。

         參見

                   setDuration(int)

 

int   LENGTH_SHORT

持續顯示視圖或文本提示較短時間。該時間長度可定制。該值為默認值。

         參見

                   setDuration(int)

7.3 Toast類的方法

 (1)public int cancel ()

如果視圖已經顯示則將其關閉,還沒有顯示則不再顯示。一般不需要調用該方法。正常情況下,視圖會在超過存續期間后消失。

 

(2)public int getDuration ()

返回存續期間

 請參閱setDuration(int)

             

(3)public int getGravity ()

 取得提示信息在屏幕上顯示的位置。      

 請參閱  Gravity setGravity()

                         

 (4)public float getHorizontalMargin ()

返回橫向欄外空白。

 

(5)public float getVerticalMargin ()

返回縱向欄外空白。

 

(6)public View getView ()

返回 View 對象。

請參閱setView(View)

 

 (7)public int getXOffset ()

返回相對於參照位置的橫向偏移像素量。

Toast msg = Toast.makeText(Main.this, "Message", Toast.LENGTH_LONG);

msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);

msg.show();              

 

(8)public int getYOffset ()

返回相對於參照位置的縱向偏移像素量。

 

(9)public static Toast makeText (Context context, int resId, int duration)

生成一個從資源中取得的包含文本視圖的標准 Toast 對象。

參數:

  context 使用的上下文。通常是你的 ApplicationActivity 對象。

  resId  要使用的字符串資源ID,可以是已格式化文本。       

  duration 該信息的存續期間。值為 LENGTH_SHORTLENGTH_LONG    

異常:

當資源未找到時拋異常Resources.NotFoundException

 

(10)public static Toast makeText (Context context, CharSequence text, int duration)

生成一個包含文本視圖的標准 Toast 對象。

參數:

context

使用的上下文。通常是你的 ApplicationActivity 對象。

resId

要顯示的文本,可以是已格式化文本。

duration

該信息的存續期間。值為 LENGTH_SHORTLENGTH_LONG

 

 

(11)public void setDuration (int duration)

設置存續期間。

請參閱

LENGTH_SHORT

LENGTH_LONG

 

(12)public void setGravity (int gravity, int xOffset, int yOffset)

設置提示信息在屏幕上的顯示位置。

(自定義Toast的顯示位置,toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0)可以把Toast定位在左上角。Toast提示的位置xOffset:大於0向右移,小於0向左移

請參閱

Gravity

getGravity()

 

(13)public void setMargin (float horizontalMargin, float verticalMargin)

設置視圖的欄外空白。

參數:

horizontalMargin  容器的邊緣與提示信息的橫向空白(與容器寬度的比)。

verticalMargin   容器的邊緣與提示信息的縱向空白(與容器高度的比)。

 

(14)public void setText (int resId)

更新之前通過 makeText() 方法生成的 Toast 對象的文本內容。

參數: resId      為 Toast 指定的新的字符串資源ID。

 

 (15)public void setText (CharSequence s)

更新之前通過 makeText() 方法生成的 Toast 對象的文本內容。

參數s   為 Toast 指定的新的文本

 

(16)public void setView (View view)

設置要顯示的 View 。

(注意這個方法可以顯示自定義的toast視圖,可以包含圖像,文字等等。是比較常用的方法。)

請參閱

getView()

 

(17)public void show ()

按照指定的存續期間顯示提示信息。

 

7.4 Toast的使用實例

我們接下來的示例要實現的是Toast的直接顯示以及toast顯示view的內容:

 首先我們在XML布局中聲明了兩個Button按鈕:

<Button android:id="@+id/button1"

   android:layout_width="fill_parent"

   android:layout_height="wrap_content"

   android:text="Toast顯示View"

/>

<Button android:id="@+id/button2"

   android:layout_width="fill_parent"

   android:layout_height="wrap_content"

   android:text="Toast直接輸出"

/>

然后在Activity中:

Button button1=(Button)findViewById(R.id.button1);

        button1.setOnClickListener(bt1lis);

        Button button2=(Button)findViewById(R.id.button2);

        button2.setOnClickListener(bt2lis);

    }

    OnClickListener bt1lis=new OnClickListener(){

 

      public void onClick(View v) {

        showToast();

      }

    };

    OnClickListener bt2lis=new OnClickListener(){

      public void onClick(View v) {

        Toast.makeText(Z_Toast1Activity.this,"直接輸出測試", Toast.LENGTH_LONG).show();

      }

    };

    public void showToast(){

      LayoutInflater li=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

      View view=li.inflate(R.layout.toast,null);

      //把布局文件toast.xml轉換成一個view

      Toast toast=new Toast(this);

      toast.setView(view);

      //載入view,即顯示toast.xml的內容

      TextView tv=(TextView)view.findViewById(R.id.tv1);

      tv.setText("Toast顯示View內容");

      //修改TextView里的內容

      toast.setDuration(Toast.LENGTH_SHORT);

      //設置顯示時間,長時間Toast.LENGTH_LONG,短時間為Toast.LENGTH_SHORT,不可以自己編輯

      toast.show();

    }

  我們實現的效果圖如下:

 

 

8 Spinner下拉列表

8.1 Spinner類的層次關系

Spinner功能類似RadioGroup,相比RadioGroup,Spinner提供了體驗性更強的UI設計模式。一個Spinner對象包含多個子項,每個子項只有兩種狀態,選擇或未被選中。Spinner類的層次關系如下:

java.lang.Object

android.view.View

  android.view.ViewGroup

    android.widget.AdapterView<T extends android.widget.Adapter>

          android.widget.AbsSpinner

             android.widget.Spinner

8.2 Spinner類的主要方法

(1)public int getBaseline()

返回這個控件文本基線的偏移量。如果這個控件不支持基線對齊,那么方法返回-1.

返回值:返回控件基線左邊邊界位置,不支持時返回-1

            (這個類不知道干什么用,只找到下面的代碼

 

(2)public CharSequence getPrompt()

返回值:    當對話框彈出的時候顯示的提示(即:獲得彈出視圖上的標題字)

 

 (3)public void onClick(DialogInterface dialog, int which)

當點擊彈出框中的項時這個方法將被調用。

參數:dialog       點擊彈出的對話框

which      點擊按鈕(如:Button)或者點擊位置

 

 (4)public Boolean performClick()

如果它被定義就調用此視圖的OnClickListener(譯者注:例如可以在加載時默認彈出下拉列表)。

 返回值  :    為True一個指定的OnClickListener被調用,為false時不被調用。

 

(5)public void setOnItemClickListener(AdapterView.OnItemClickListener  I)

        Spinner不支持item的點擊事件,調用此方法將引發異常。

參數:l    這個監聽將被忽略

      

(6)public void setPromptId(CharSequence prompt)

設置對話框彈出的時候顯示的提示(譯者注:設置彈出視圖上的標題字)

參數

prompt     設置的提示

 

(7)public void setPromptId(int promptId)

設置對話框彈出的時候顯示的提示(譯者注:設置彈出視圖上的標題字)

參數:prompted 當對話框顯示是顯示這個資源id所代表的提示。

 

 受保護的方法

(8)protected void onDetachedFromWindow ()

當這個視圖從屏幕上卸載時候被調用。在這一點上不再繪制視圖。

 

(9)protected void onLayout(boolean changed, int l, int t, int r, int b)

當View要為所有子對象分配大小和位置時,調用此方法。派生類與子項們應該重載這個方法和調用布局每一個子項。

 參數:changed   這是這個視圖的一個新的大小或位置

l        相對父空間的左位置

t        相對父空間的頂端位置

r        相對父空間的右端位置

b       相對父空間的底部位置

 

參見

Creates and positions all views

 

8.3 Spinner類的屬性

XML屬性

屬性名稱

描述

android:prompt

該提示在下拉列表對話框顯示時顯示。(也就是對話框的標題:

 

 

 

8.4 Spinner的使用示例

首先我們在Xml中聲明Spinner,這里同時聲明了一個TextView方便等下顯示Spinner的監聽結果:

<TextView  android:id="@+id/TextView01"

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

      android:text="@string/hello"/>

<Spinner android:id="@+id/Spinner01"

   android:layout_width="300dip"

   android:layout_height="wrap_content">

</Spinner>

 

然后就可以在Activity中使用了:

final TextView textview = (TextView)findViewById(R.id.TextView01);

        Spinner spinner = (Spinner) findViewById(R.id.Spinner01);  

        final List<String> list  = new ArrayList<String>();

        list .add("Spinner子項1");

        list .add("Spinner子項2");

        list .add("Spinner子項3");

        //將可選內容list與ArrayAdapter相連接

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list );

        //設置下拉列表的風格

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

       //將Adapter添加到Spinner

        spinner.setAdapter(adapter);

 

好了,到這步以及在屏幕上可以顯示出Spinner了,接下來就是添加事件監聽了

        //添加事件監聽

spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){

        @Override

        public void onItemSelected(AdapterView<?> arg0, View arg1,

              int arg2, long arg3) {

           // TODO Auto-generated method stub

           textview.setText("你當前選擇的是: "+list.get(arg2));

        }

        @Override

        public void onNothingSelected(AdapterView<?> arg0) {

           // TODO Auto-generated method stub

          

        }

                  });

示例的使用效果圖如下:

 

 

9 ListView列表

9.1 ListView類的層次關系

ListView是用來顯示一個列表的控件,以下是ListView類的層次關系:

java.lang.Object

   android.view.View     

     android.view.ViewGroup             

        android.widget.AdapterView<T extends android.widget.Adapter>                       android.widget.AbsListView                           android.widget.ListView

直接子類

         ExpandableListView (使用豎滾動條查看的兩級列表視圖)

 

9.2 ListView的所有方法

公共方法

        (1)public void addFooterView (View v)

         加一個固定顯示於list底部的視圖。如果此方法被調用超過一次,所加的幾個視圖將按照它們加入的順序排列。加入的視圖可取得焦點。

         注意:在調用setAdapter之前調用此方法。這樣的話,可以利用點擊光標來收起有header view和footer view的ListView。

參數:v      要加的視圖

                           

(2)public void addFooterView (View v, Object data, boolean isSelectable)

         加一個固定顯示於list底部的視圖。如果此方法被調用超過一次,所加的幾個視圖將按照它們加入的順序排列。加入的視圖可取得焦點。

         注意:在調用setAdapter之前調用此方法。這樣的話,可以利用點擊光標來收起有header view和footer view的ListView。

參數:v                         要加的視圖

                     data                   和此視圖關聯的數據     

     isSelectable      設為true則表示footer view可以被選中                     

                           

(3)public void addHeaderView (View v)

         加一個固定顯示於list頂部的視圖。如果此方法被調用超過一次,所加的幾個視圖將按照它們加入的順序排列。加入的視圖可取得焦點。

         注意:在調用setAdapter之前調用此方法。這樣的話,可以利用點擊光標來收起有header view和footer view的ListView。

    參數:v      要加的視圖

                           

(4)public void addHeaderView (View v, Object data, boolean isSelectable)

         加一個固定顯示於list頂部的視圖。如果此方法被調用超過一次,所加的幾個視圖將按照它們加入的順序排列。加入的視圖可取得焦點。

         注意:在調用setAdapter之前調用此方法。這樣的話,可以利用點擊光標來收起有header view和footer view的ListView。

    參數:v                         要加的視圖

                     data                   和此視圖關聯的數據    

                     isSelectable      表示此header view可選與否   

                           

(5)public void clearChoices ()

         取消之前設置的任何選擇

 

(6)public boolean dispatchKeyEvent (KeyEvent event)

         按照可以獲得焦點的順序(從視圖樹的頂端到當前獲得焦點的視圖),分派一個按鍵事件給下一個視圖。若此視圖有焦點,事件將會分派給它自己。否則它將按照順序,分派給下一個節點。此方法同時觸動所有按鍵監聽器。

         參數:event                 被分派的事件

         返回:若事件被處理,則返回true;否則為false

                  

(7)public boolean dispatchPopulateAccessibilityEvent (AccessibilityEvent event)

         在視圖的子項目被構建時,分派一個輔助事件。

                  參數:event                 事件

                  返回:若事件全部完成,則返回true

                           

(8)public ListAdapter getAdapter ()

         返回ListView當前用的適配器。返回的適配器不可以和傳給setAdapter(ListAdapter)的參數一樣,但是可以是WrapperListAdapter。

                  返回:當前用來顯示ListView中數據的適配器

                  參見:setAdapter(ListAdapter)

                           

(9)public long[] getCheckItemIds ()

此方法已經過時了。使用getCheckedItemIds()代替。

         返回被選中項目的索引集合。只有當選擇模式沒有被設置為CHOICE_MODE_NONE時才有效。

 

(10)public long[] getCheckedItemIds ()

         返回被選中項目的索引集合。只有當選擇模式沒有被設置為CHOICE_MODE_NONE,並且適配器有穩定的 ID(hasStableIds()==true) 時,結果才有效。

         返回

                   一個新的數組,包含列表中每個被選中的索引(id)

 

(11)public int getCheckedItemPosition ()

         返回當前被選中的項目。只有當選擇模式已被設置為CHOICE_MODE_SINGLE時 ,結果才有效。

                  返回:

                            返回當前被選中的項目的索引;若沒有項目被選中,則返回INVALID_POSITION

                  參見

                            setChoiceMode(int)

 

(12)public SparseBooleanArray getCheckedItemPositions ()

         返回當前被選中的項目集合。只有當選擇模式沒有被設置為CHOICE_MODE_NONE時 ,結果才有效。

                  返回

                            類型為SparseBooleanArray的值,其中,對每一個索引所代表的項目,若被選中,則返回true;當選擇模式被設置為CHOICE_MODE_NONE時 ,返回null。

 

(13)public int getChoiceMode ()

                  返回

                            返回當前的選擇模式

                  參見

                            setChoiceMode(int)

 

(14)public Drawable getDivider ()

                  返回

                            返回當前畫在列表元素之間,作為分隔符的圖形

 

(15)public int getDividerHeight ()

                  返回

                            返回分隔符的高度

 

(16)public int getFooterViewsCount ()

                  返回

                            列表中的頁腳視圖數量;缺省實現時,數量為0

 

(17)public int getHeaderViewsCount ()

                  返回

                            列表中的頁眉視圖數量;缺省實現時,數量為0

 

(18)public boolean getItemsCanFocus ()

                  返回

                            ListAdapter所生成的視圖是否可以包含能取得焦點的項目

 

(19)public int getMaxScrollAmount ()

         返回

                   The maximum amount a list view will scroll in response to an arrow event.

                   響應箭頭事件時,列表視圖可以滾動的最大值。(譯者注:此處翻譯待改進,恐怕需要仔細查看源代碼才能明白其含義,也可以用Google Code搜索相關的代碼)

 

(20)public boolean isItemChecked (int position)

         對於由position指定的項目,返回其是否被選中。只有當選擇模式已被設置為CHOICE_MODE_SINGLE或CHOICE_MODE_MULTIPLE時 ,結果才有效。

                  參數

                            position                      要返回選中狀態的項目

                  返回

                            返回項目的選中狀態;若選擇模式無效,則返回false

 

(21)public boolean onKeyDown (int keyCode, KeyEvent event)

         KeyEvent.Callback.onKeyMultiple()的缺省實現:若視圖被激活並且可以被點擊,當出現KEYCODE_DPAD_CENTER和KEYCODE_ENTER代表的行為時,做點擊該視圖的動作。

                  參數

                            keyCode                     表示按某個按鍵的按鍵代號,參見KeyEvent

                            event                           定義按鍵動作的按鍵事件對象

                  返回

                            若事件被成功處理,則返回true;若想要下一個接收器處理該事件,則返回false

 

(22)public boolean onKeyMultiple (int keyCode, int repeatCount, KeyEvent event)

         KeyEvent.Callback.onKeyMultiple()的缺省實現:總是返回false(不處理該事件)。

                  參數

                            keyCode                     表示按某個按鍵的按鍵代號,參見KeyEvent

                            repeatedCount         實現動作的次數

                            event                           定義按鍵動作的按鍵事件對象

                  返回

                            若事件被成功處理,則返回true;若想要下一個接收器處理該事件,則返回false

 

(23)public boolean onKeyUp (int keyCode, KeyEvent event)

         KeyEvent.Callback.onKeyMultiple()的缺省實現:當出現KEYCODE_DPAD_CENTER和KEYCODE_ENTER代表的行為時,做點擊該視圖的動作。

                  參數

                            keyCode                     表示按某個按鍵的按鍵代號,參見KeyEvent

                            event                           定義按鍵動作的按鍵事件對象

                  返回

                            若事件被成功處理,則返回true;若想要下一個接收器處理該事件,則返回false

 

(24)public void onRestoreInstanceState (Parcelable state)

         重新創建並顯示一個視圖,此視圖擁有之前onSaveInstanceState()保存的內部狀態。當state為null時,此方法不會被調用。

                  參數

                            state                           之前onSaveInstanceState()保存的狀態

 

(25)public Parcelable onSaveInstanceState ()

         保存視圖的內部狀態,用於以后創建新的擁有同樣狀態的實例。可保存的狀態只包含非持久性的,或者可重新組建的信息。比如,永遠不可能保存你當前在屏幕上的位置,因為當新的實例被放置於視圖層次體系中時,位置會被重新計算。

         一些可以被保存的狀態:文本視圖(但是通常不是指文本本身,因為文本是被保存在內容提供商或其他持久性的儲存體中)中當前的光標位置;列表視圖中當前的選中項。

返回                  

返回一個包含視圖當前動態狀態的接口方法對象;若沒有東西被保存,則返回null。缺省情況下返回null。

 

(26)public boolean onTouchEvent (MotionEvent ev)

         此方法用於處理觸摸屏的動作事件。

                  參數

                            ev                        動作事件

                  返回

                            若事件被成功處理,則返回true;否則返回false

 

(27)public boolean performItemClick (View view, int position, long id)

         調用定義好的OnItemClickListener。

                  參數

                            view                   AdapterView中被點擊到的視圖

                            position             視圖在適配器中的索引

                            id                         被點擊到的項目的行id

                  返回

                            若有定義好的OnItemClickListener被成功調用,則返回true;否則返回false

 

(28)public boolean removeFooterView (View v)

         刪除之前加入的某個頁腳視圖。

                  參數

                            v                 要刪除的視圖

                  返回

                            若視圖被成功刪除,則返回true;若此視圖不是頁腳視圖,則返回false

 

(29)public boolean removeHeaderView (View v)

         刪除之前加入的某個頁眉視圖。

                  參數

                            v                 要刪除的視圖

                  返回

                            若視圖被成功刪除,則返回true;若此視圖不是頁眉視圖,則返回false             

(30)public boolean requestChildRectangleOnScreen (View child, Rect rect, boolean immediate)

         當組里的某個子項需要被定位在屏幕的某個矩形范圍時,調用此方法。    

         重載此方法的ViewGroup可確認以下幾點:

                   · 子項目將是組里的直系子項

                   · 矩形將在子項目的坐標體系中

         重載此方法的ViewGroup必須保證以下幾點:

                   · 若矩形已經是可見的,則沒有東西會改變

                   · 為使矩形區域全部可見,視圖將可以被滾動顯示

                  參數

                            child                   發出請求的子項目

                            rect                    子項目坐標系內的矩形,即此子項目希望在屏幕上的定位

                            immediate        設為true,則禁止動畫和緩釋移動滾動條

                  返回

                            這個可滾動顯示的組,是否接受請求

 

(31)public void setAdapter (ListAdapter adapter)

         設置ListView背后的數據。根據ListView目前使用的特性,adapter可能被WrapperListAdapter收起。例如:加頁眉和/或頁腳會使adapter被收起。

                  參數

                            adapter             負責維護列表背后的數據,以及生成視圖來顯示數據里的項目

                  參見

                            getAdapter()            

 

(32)public void setCacheColorHint (int color)

         當color的值不為0時,此值表示的顏色將提示使用者,列表正在一片單色不透明的背景上被畫出。

                  參數

                            color                   背景色

 

(33)public void setChoiceMode (int choiceMode)

         設置List的選擇模式。缺省情況下,列表沒有選擇模式(即值為CHOICE_MODE_NONE)。

                  參數

                            choiceMode              值可為CHOICE_MODE_NONE,CHOICE_MODE_NONE和CHOICE_MODE_NONE中的一種

 

(34)public void setDivider (Drawable divider)

         設置將畫在列表中每個項目之間的圖形。如果圖形沒有已設定好的高度,則必須同時調用setDividerHeight(int)。

                  參數

                            divider               將用作分隔符的圖形

 

(35)public void setDividerHeight (int height)

         設置分隔符(畫在列表中每個項目之間)的高度。調用此方法將覆蓋由setDivider(Drawable)設置的高度。

                  參數

                            height       分隔符的新高度,單位為像素

 

(36)public void setFooterDividersEnabled (boolean footerDividersEnabled)

         設置可以或者不可以為頁腳視圖畫上分隔符。

                  參數

                            headerDividersEnabled            設為true,表明可以畫;設為false則不可以

                  參見

                            setHeaderDividerEnabled(boolean)

                            addFooterView(android.view.View)

 

(37)public void setHeaderDividersEnabled (boolean headerDividersEnabled)

         設置可以或者不可以為頁眉視圖畫上分隔符。

                  參數

                            headerDividersEnabled            設為true,表明可以畫;設為false則不可以

                  參見

                            setFooterDividerEnabled(boolean)

                            addHeaderView(android.view.View)

 

(38)public void setItemChecked (int position, boolean value)

         設置position所指定項目的選擇狀態。只有選擇模式為CHOICE_MODE_SINGLE或者CHOICE_MODE_MULTIPLE時,此設置才有效。

                  參數

                            position             需要改變選擇狀態的項目的索引

                            value                  新的選擇狀態

 

(39)public void setItemsCanFocus (boolean itemsCanFocus)

         表明在由ListAdapter創建的視圖中,可包含能獲得焦點的項目。

                  參數

                            itemsCanFocus         若項目能獲得焦點,則設為true;否則為false

 

(40)public void setSelection (int position)

         選中position指定的項目。若為觸摸模式,則指定項目不會被選中,但位置變化一樣。若position的值小於0,則position為0的項目將被選中。

                  參數

                            position             需要選中的項目的索引(從0開始)

 

(41)public void setSelectionAfterHeaderView ()

         選中頁眉視圖下的第一個列表項目。

 

(42)public void setSelectionFromTop (int position, int y)

         選中position指定的項目,並將所選項置於距離ListView頂端y像素的位置(若為觸摸模式,則指定項目不會被選中,但位置變化一樣)。

                  參數

                            position             需要選中的項目的索引(從0開始)

                            y                       距離ListView(包括間隙)頂端的位置

 

受保護方法

        (43) protected boolean canAnimate ()

         表示此視圖組是否可以在第一次被布局后,仍可以動態調整其子項。

                  返回

                            若可以則為true,否則為false

 

(44)protected void dispatchDraw (Canvas canvas)

         調用此方法來繪出子視圖。可被衍生類重寫,以便在其子項被畫出之前取得控制權。

                  參數

                            canvas              繪出View所用的canvas(畫布?)

 

(45)protected View findViewTraversal (int id)

                  參數

                            id                         要找的View的id

                  返回值

                            有此id的View,若沒有找到則為null

 

(46)protected View findViewWithTagTraversal (Object tag)

                  參數

                            tag                    要找的View的標簽

                  返回值

                            有此標簽的View,若沒有找到則為null

 

(47)protected void layoutChildren ()

         子類必須重寫此方法來布局其子項。

        

(48)protected void onFinishInflate ()

         當View以及所有子項從XML中導入時被調用,是導入的最后一步。即使子類重寫onFinishInflate,也必須保證有調用超方法,這樣,方法才會被調用。

        

(49)protected void onFocusChanged (boolean gainFocus, int direction, Rect previouslyFocusedRect)

         當View的焦點改變時被調用。重寫時,要確保超類的直接調用,這樣取得焦點的方式才是標准的。

參數

                            gainFocus        若View有焦點,則為True;否則為False。

                            direction           當requestFocus()被調用時,方向焦點被移動。其值可為FOCUS_UP,FOCUS_DOWN,FOCUS_LEFT或FOCUS_RIGHT。在使用缺省條件的情況下,direction並不總是可用。

                            previouslyFocusedRect    之前得到焦點的View的坐標系統所構成的矩形。如果可用,這個將被當成精確信息(表明焦點從何而來以及從何方向而來)來傳遞;否則將傳遞null。

 

(50)protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)

         View調用此方法來確定本身和所包含內容的大小。此方法被measure(int,int)喚起,而且必須被子類重寫以得到所包含內容的確切大小。

         注意:當重寫此方法時,必須調用setMeasureDimension(int,int)來保存View的大小。如果沒有做到,將會引發一個measure(int,int)拋出的IllegalStateException(非法狀態錯誤)。超類onMeasure(int,int)可以被調用。

         編寫基類的確認大小的方法,缺省情況下是根據其背景大小來確認,除非MeasureSepc允許有更大的高度或寬度。子類必須重寫onMeasure(int,int)以得到對其內容大小的更准確的測量。

         若此方法被重寫,它的子類需要確保其高度和寬度至少達到View所規定的最小值(可通過getSuggestedMinimumHeight()和getSuggestedMinimumWidth()得到)。

參數

                            widthMeaureSpec           受上一層大小影響下的對水平空間的要求。可參看View.MeasureSpec。

                            heightMeasureSpec         受上一層大小影響下的對垂直空間的要求。可參看View.MeasureSpec。

                           

protected void onSizeChanged (int w, int h, int oldw, int oldh)

         當VIew的大小改變時此方法被調用。如果VIew是剛剛被加入,則視之前的值為0。

參數

                            w                       View的當前寬度

                            h                          View的當前高度

                            oldw                   View大小改變之前的寬度

                            oldh                    View大小改變之前的高度

 

9.3 ListView的屬性及包含的幾個常量

XML屬性

 

屬性名稱

描述

android:choiceMode

規定此ListView所使用的選擇模式。缺省狀態下,list沒有選擇模式。

屬性值必須設置為下列常量之一: none,值為0,表示無選擇模式;

singleChoice,值為1,表示最多可以有一項被選中;

multipleChoice,值為2,表示可以多項被選中。

可參看全局屬性資源符號choiceMode。

android:divider

規定List項目之間用某個圖形或顏色來分隔。可以用"@[+][package:]type:name"或者"?[package:][type:]name"(主題屬性)的形式來指向某個已有資源;也可以用"#rgb","#argb","#rrggbb"或者"#aarrggbb"的格式來表示某個顏色。

可參看全局屬性資源符號divider。

android:dividerHeight

分隔符的高度。若沒有指明高度,則用此分隔符固有的高度。必須為帶單位的浮點數,如"14.5sp"。可用的單位如px(pixel像素),dp(density-independent pixels 與密集度無關的像素),  sp(scaled pixels based on preferred font size 基於字體大小的固定比例的像素), in (inches英寸), mm (millimeters毫米)。

可以用"@[package:]type:name

"或者"?[package:][type:]name"(主題屬性)的格式來指向某個包含此類型值的資源。

可參看全局屬性資源符號dividerHeight。

android:entries

引用一個將使用在此ListView里的數組。若數組是固定的,使用此屬性將比在程序中寫入更為簡單。

必須以"@[+][package:]type:name"或者 "?[package:][type:]name"的形式來指向某個資源。

可參看全局屬性資源符號entries。

android:footerDividersEnabled

設成flase時,此ListView將不會在頁腳視圖前畫分隔符。此屬性缺省值為true。

屬性值必須設置為true或false。

可以用"@[package:]type:name

"或者"?[package:][type:]name"(主題屬性)的格式來指向某個包含此類型值的資源。

可參看全局屬性資源符號footerDividersEnabled。

android:headerDividersEnabled

設成flase時,此ListView將不會在頁眉視圖后畫分隔符。此屬性缺省值為true。

屬性值必須設置為true或false。

可以用"@[package:]type:name

"或者"?[package:][type:]name"(主題屬性)的格式來指向某個包含此類型值的資源。

可參看全局屬性資源符號headerDividersEnabled。

 

常量:

  Int    CHOICE_MODE_MULTIPLE    

(常量值為2)列表允許同時選取多項

Int    CHOICE_MODE_NONE            

(常量值為0)普通列表,不指明選取模式

Int    CHOICE_MODE_SINGLE         

(常量值為1)列表只允許選取最多一項

 

9.4 ListView的使用示例

首先在XML中聲明一個ListView,一個TextView用來顯示ListView的監聽結果:

<TextView  android:id="@+id/TextView01"

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

      android:text="@string/hello" />

   <ListView android:id="@+id/ListView01"

      android:layout_width="wrap_content"

      android:layout_height="wrap_content">

   </ListView>

然后在Avticity中:

final TextView textView = (TextView)findViewById(R.id.TextView01);

        ListView listView = (ListView)findViewById(R.id.ListView01);

        //創建數組list,用於存放要顯示的內容

        final List<String> list  = new ArrayList<String>();

        list.add("ListView子項1");

        list.add("ListView子項2");

        list.add("ListView子項3");

        //將數據與適配器adapter連接

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, list );

       //將adapter添加到ListView

        listView.setAdapter(adapter);

       

        //實現ListView的監聽

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){

 

        @Override

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,

              long arg3) {

           // TODO Auto-generated method stub

           textView.setText("你當前選擇的是"+list.get(arg2).toString());

        }

         

        });

       

示例的效果圖如下:

 

9.5關於ListView使用的參考鏈接

Android入門第六篇之ListView (一)

                   android ListView詳解

                   android異步加載ListView中的圖片

                   Google I/O 2010 - The world of ListView

                   Android: 顯示SD卡文件列表

                   Android: 帶圖標的ListView實現

ListView和getView的原理+如何在ListView中放置多個item

 

10 TabHost標簽頁

10.1 TabHost類的層次關系

繼承關系

public class TabHost extends FrameLayout implements ViewTreeObserver.OnTouchModeChangeListener

        

java.lang.Object

android.view.View

        android.view.ViewGroup

                android.widget.FrameLayout

                        android.widget.TabHost

10.2 TabHost常用的方法

內部類

interface TabHost.OnTabChangeListener    

接口定義了當選項卡更改時被調用的回調函數

 

interface TabHost.TabContentFactory  

當某一選項卡被選中時生成選項卡的內容

 

class TabHost.TabSpec     

單獨的選項卡,每個選項卡都有一個選項卡指示符,內容和tag標簽,以便於記錄.

 

公共方法

(1)public void addTab (TabHost.TabSpec tabSpec)

新增一個選項卡

參數

tabSpec    指定怎樣創建指示符和內容.

 

(2)public void clearAllTabs ()

從tab widget中移除所有關聯到當前tab host的選項卡

 

(3)public boolean dispatchKeyEvent (KeyEvent event)

分發按鍵事件到焦點傳遞路線上的下一視圖。焦點傳遞路線從視圖樹的頂層開始一直到當前獲取焦點的視圖停止。如果此視圖已經獲取焦點,將分發給它自身。否則,將分發到焦點傳遞路線的下一節點。此方法會觸發任何一個按鍵監聽器.

(譯者注:關於focus path,可以參考以下地址:

http://blog.csdn.net/maxleng/archive/2010/05/04/5557758.aspx)

參數

event        分發的按鍵事件

返回值

如果事件已經處理則返回true,否則返回false.

 

(4)public void dispatchWindowFocusChanged (boolean hasFocus)

當窗口包含的此視圖獲取或丟失焦點時觸發此方法.ViewGroups應該重寫以路由到他的子元素

參數

hasFocus 如果窗口包含的此view依獲取焦點,返回true,否則返回false.

 

(5)public int getCurrentTab ()

(譯者注:獲取當前選項卡的id)

 

(6)public String getCurrentTabTag ()

(譯者注:當前選項卡的Tag標簽內容)

 

(7)public View getCurrentTabView ()

(譯者注:獲取當前選項卡的視圖view)

 

(8)public View getCurrentView ()

(譯者注:獲取當前的視圖view)

 

(9)public FrameLayout getTabContentView ()

獲取保存tab內容的FrameLayout

 

(10)public TabWidget getTabWidget ()

(譯者注:根據系統規定的id:tabs來找到TabWidget,並返回,注意,這里的ID必須是tabs。源代碼中表示如下:

private TabWidget mTabWidget;

mTabWidget=(TabWidget)findViewById(com.android.internal.R.id.tabs);

 

(11)public TabHost.TabSpec newTabSpec (String tag)

獲取一個新的TabHost.TabSpec,並關聯到當前tab host

參數

tag   所需的選項卡標簽(tag)

 

(12)public void onTouchModeChanged (boolean isInTouchMode)

當觸摸模式發生改變時調用的回調函數.

參數

isInTouchMode         如果視圖結構當前處於觸摸模式,返回true,否則返回false.

 

(13)public void setCurrentTab (int index)

(譯者注:設置當前的選項卡

參數

Index        為當前選項卡的索引。)

 

(14)public void setCurrentTabByTag (String tag)

(譯者注:根據選項卡的Tab標簽來設置當前的選項卡

                            參數

tag  想要被設置為當前選項卡的tag標簽值。)

 

(15)public void setOnTabChangedListener(TabHost.OnTabChangeListener l)

注冊一個回調函數,當選項卡中的任何一個tab的選中狀態發生改變時調用。

(譯者注:setCurrentTab(index)時會觸發調用)

參數

l        將運行的回調函數

        

(16)public void setup ()

如果使用findViewById()加載TabHost,那么在新增一個選項卡tab之前,需要調用setup()。然而,當你在一個TabActivity里使用getTabHost()獲取TabHost,你就不再需要調用setup()了。(譯者注:實現tab窗口的兩種方法:繼承activity時,使用findViewById()查找TabHost,然后調用setup();繼承TabActivity,通過getTabHost()查找,此時不用調用setup())例子:

 

 

(17)public void setup (LocalActivityManager activityGroup)

如果你使用setContent(android.content.Intent),那么當activityGroup用於加載本地activity之時,必須調用此方法。如果你拓展(繼承)TabActivity將自動調用setup()方法。

參數

activityGroup   用來為選項卡內容加載activities的ativityGroup

 

受保護方法

protected void onAttachedToWindow ()

當視圖附加到窗口上時被調用。在這個點的表面進行繪制。注意此函數確保在onDraw(Cancas)之前調用,然而它可能在第一次執行onDraw之前的任何時間被調用——包括的onMeasure(int,int)的之前或之后。

 

protected void onDetachedFromWindow ()

當視圖從窗口分離時被調用。在這個點的表面不再有畫面繪制。

 

10.3 TabHost的使用示例

我們這里使用3個XML來實現

tab1.xml文件代碼:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout android:id = "@+id/layout01"

  ……

  ……

</LinearLayout>

tab2.xml文件代碼:

<?xml version="1.0" encoding="utf-8"?>

<AbsoluteLayout android:id="@+id/layout02"

  ……

  ……

</AbsoluteLayout>

tab3.xml文件代碼:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout android:id="@+id/layout03"

  ……

……

</RelativeLayout>

 

注意:在Activity中我們繼承的是TabActivity:

public class TabDemo extends TabActivity {

TabHost tabHost = getTabHost();

        LayoutInflater.from(this).inflate(R.layout.tab1,
                      tabHost.getTabContentView(),true);

        LayoutInflater.from(this).inflate(R.layout.tab2,
                      tabHost.getTabContentView(),true);

        LayoutInflater.from(this).inflate(R.layout.tab3,
                      tabHost.getTabContentView(),true);

        tabHost.addTab(tabHost.newTabSpec("TAB1")

               .setIndicator("線性布局").setContent(R.id.layout01));

        tabHost.addTab(tabHost.newTabSpec("TAB2")

               .setIndicator("絕對布局").setContent(R.id.layout02));

        tabHost.addTab(tabHost.newTabSpec("TAB3")

               .setIndicator("相對布局").setContent(R.id.layout03));

 

 

 

10.4 補充

補充

文章鏈接

         史上最全的Android的Tab與TabHost講解

         Android UI設計 Tab TabHost標簽頁的使用

         Android 控件之TabHost Tab頁

動態Tab頁

 

 

11 LinearLayout線性布局

11.1 線性布局介紹

LinearLayout是一種線性排列的布局,在線性布局中,所有的子元素都按照垂直或水平的順序在界面上排列:

如果垂直排列,則每行僅包含一個界面元素,如果水平排列,則每列僅包含一個界面元素。可以通過屬性android:orientation定義布局中子元素的排列方式。android.widget.LinearLayout類是android.view.viewGroup的子類,其中又派生了RadioGroup、TabWidget、TableLayout、TableRow、ZoomControls等類。

11.2 線性布局的常用屬性

  Android:id       為控件指定相應的ID

 

 Android:text      指定控件當中顯示的文字,需要注意的是,這里盡量使用strings.xml文件當中的字符

 

Android:grivity     指定控件的基本位置,比如說居中,居右等位置Android:textSize    指定控件當中字體的大小                      Android:background     指定該控件所使用的背景色,RGB命名法

Android:width          指定控件的寬度

Android:height        指定控件的高度

Android:padding*      指定控件的內邊距,也就是說控件當中的內容

Android:sigleLine   如果設置為真的話,則將控件的內容在同一行當中進行顯示   

 

 

 

11.3 Linear常用的方法

方法

功能描述

返回值

LinearLayout

兩個構造函數:

LinearLayout(Contex context)

LinearLayout(Contex contex,AttributeSet attrs)

null

getOrientation()

獲取布局的方向設置。0代表水平方向,1代表垂直方向

int

isBaselineAligned()

判斷布局是否按照基線對齊

boolean

setBaselineAligned(boolen baselineAligned)

根據參數設置基線對齊

void

setGravity(int gravity)

根據指定的重力設置元素的大小

void

setHorizontalGravity(int gravity)

設置水平方向的重力

void

setVerticalGravity(int gravity)

設置垂直方向的重力

void

gennerateDefaultLayoutParams

返回包含寬度和高度的布局參數的集合

LayoutParams

setGravity(int gravity)

設置布局的重力

void

 

 

 

 

11.4 LinearLayout的使用

在XML中設置如下:

<!-- 水平線性布局 -->

   <LinearLayout android:layout_height="100dip"

      android:orientation="horizontal" android:layout_width="fill_parent">

      <TextView android:background="#aa0000" android:layout_width="wrap_content"

        android:gravity="center_horizontal" android:text="第一列"

        android:layout_weight="1" android:layout_height="50dip"></TextView>

      <TextView android:background="#00aa00" android:layout_width="wrap_content"

        android:gravity="center_horizontal" android:text="第二列"

        android:layout_weight="1" android:layout_height="50dip"></TextView>

      <TextView android:background="#0000aa" android:layout_width="wrap_content"

        android:gravity="center_horizontal" android:text="第三列"

        android:layout_weight="1" android:layout_height="50dip"></TextView>

   </LinearLayout>

 

<!-- 垂直線性布局 -->

<LinearLayout

    android:layout_height="100dip"

      android:orientation="vertical" android:layout_width="fill_parent">

      <TextView android:background="#aa0000" android:layout_width="fill_parent"

        android:gravity="center_horizontal" android:text="第一行"

        android:layout_weight="1" android:layout_height="50dip"></TextView>

      <TextView android:background="#00aa00" android:layout_width="fill_parent"

        android:gravity="center_horizontal" android:text="第二行"

        android:layout_weight="1" android:layout_height="50dip"></TextView>

      <TextView android:background="#0000aa" android:layout_width="fill_parent"

        android:gravity="center_horizontal" android:text="第三行"

        android:layout_weight="1" android:layout_height="50dip"></TextView>

   ></LinearLayout>

 

然后在就可以直接顯示:

 

 

 

12 FrameLayout框架布局

12.1 FrameLayout的簡單介紹

FrameLayout是布局中最簡單的一個布局,在這個布局中,整個界面被當成一塊空白備用區域,所有的子元素都不能被指定放置的位置,它們統統放於這塊區域的左上角,並且后面的子元素直接覆蓋在前面的子元素之上,將前面的子元素部分和全部遮擋。

 

12.2 FrameLayout的使用

FrameLayout的使用很簡單,在XML中的聲明為FrameLayout就可以:

<?xml version="1.0" encoding="utf-8"?>

 

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    >

<TextView 

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:textSize="50dip"

    android:textColor="#ffffff"

    android:text="第一層"/>

<TextView 

 

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:textSize="40dip"

    android:textColor="#ffff00"

    android:text="第二層"/>

<TextView 

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:textSize="30dip"

    android:textColor="#ff00ff"

    android:text="第三層"/>

<TextView 

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:textSize="20dip"

    android:textColor="#00ffff"

    android:text="第四層"/>

</FrameLayout>

 

 

13 TableLayout表格布局

13.1 TableLayout的層次關系

 

表格布局(TableLayout)也是一種常用的界面布局,它將屏幕划分網格,通過指定行和列可以將界面元素添加的網格中。

 

 
   

 

 

 

 

 

 

 

 

 

TableLayout事實上是LinearLayout的子類,它的層次關系如下:

java.lang.Object

 android.view.View

   android.widget.ViewGroup

     android.widget.LinearLayout

       android.widget.TableLayout

 

 

 

13.2 TableLayout常用的方法

構造函數

public TableLayout (Context context)

為給定的上下文創建表格布局。

                   參數

context   應用程序上下文

 

public TableLayout (Context context, AttributeSet attrs)

使用指定的屬性集合為給定的上下文創建表格布局。

                   參數

context   應用程序上下文

attrs        屬性集合

 

公共方法

public void addView (View child)

添加子視圖。如果子視圖沒有設置布局參數,則使用視圖組(ViewGroup)的布局參數為該視圖布局。

                   參數

child         添加的子視圖

 

public void addView (View child, int index)

添加子視圖。如果子視圖沒有設置布局參數,則使用視圖組(ViewGroup)的布局參數為該視圖布局。

                   參數

child         添加的子視圖

index       子視圖加入的位置索引

 

public void addView (View child, int index, ViewGroup.LayoutParams params)

用指定的布局參數添加一個子視圖。

                   參數

child         添加的子視圖

index       子視圖加入的位置索引

params   為子視圖指定得布局參數

 

public void addView (View child, ViewGroup.LayoutParams params)

使用指定的布局參數添加子視圖。

                   參數

child         添加的子視圖

params   設置到子視圖上的布局參數

 

public TableLayout.LayoutParams generateLayoutParams (AttributeSet attrs)

返回一組基於提供的屬性集合的布局參數集合。

                   參數

attrs        用於生成布局參數的屬性集

返回值

                       ViewGroup.LayoutParams或其子類的實例

 

public boolean isColumnCollapsed (int columnIndex)

返回指定列的折疊狀態。

                   參數

columnIndex   列索引

返回值

折疊時為true;否則為false

 

public boolean isColumnShrinkable (int columnIndex)

返回指定的列是否可收縮。

                   參數

columnIndex   列索引

返回值

                       如果列可以收縮,返回true;否則返回false

 

public boolean isColumnStretchable (int columnIndex)

返回指定的列是否可拉伸。

                   參數

columnIndex   列索引

返回值

如果列可以拉伸,返回true;否則返回false

 

public boolean isShrinkAllColumns ()

指示是否所有的列都是可收縮的。

返回值

                       如果所有列都可收縮,返回true;否則返回false

 

public boolean isStretchAllColumns ()

指示是否所有的列都是可拉伸的。

返回值

                       如果所有列都可拉伸,返回true;否則返回false

 

public void requestLayout ()

當某些變更導致視圖的布局失效時調用該方法。該方法按照視圖樹的順序調用。

 

public void setColumnCollapsed (int columnIndex, boolean isCollapsed)

折疊或恢復給定列。折疊時,列從屏幕上消失,其空間由其它列占用。 當列屬於 TableRow 時才可以進行折疊/恢復操作。

調用該方法會請求布局操作。

                 相關XML屬性

                       android:collapseColumns

                   參數

columnIndex   列索引

isCollapsed     折疊時為true;否則為false

 

public void setColumnShrinkable (int columnIndex, boolean isShrinkable)

設置指定列是否可收縮。當行太寬時,表格可以收縮該列以提供更多空間。

調用該方法會請求布局操作。

                   相關XML屬性

                            android:shrinkColumns

                   參數

columnIndex   列索引

isShrinkable    如果列可以收縮,設為真;否則設為假。默認是假。

 

public void setColumnStretchable (int columnIndex, boolean isStretchable)

設置指定列是否可拉伸。可拉伸時,列會盡可能多的占用行中的可用空間。

調用該方法會請求布局操作。

                   相關XML屬性

                            android:stretchColumns

                   參數

columnIndex   列索引

isStretchable 如果列可以拉伸,設為真;否則設為假.默認是假

 

public void setOnHierarchyChangeListener (ViewGroup.OnHierarchyChangeListener listener)

注冊當從視圖中添加或移除子視圖時發生的回調函數。

                   參數

listener   層次結構變更時執行的回調函數

 

public void setShrinkAllColumns (boolean shrinkAllColumns)

標記所有列為可收縮的便利的方法。

                   相關XML屬性

android:shrinkColumns

                   參數

shrinkAllColumns    如果標記所有列為可收縮時為true

 

public void setStretchAllColumns (boolean stretchAllColumns)

標記所有列為可拉伸的便利的方法。

                   相關XML屬性

                            android:stretchColumns

                   參數

stretchAllColumns           如果標記所有列為可拉伸時為true

 

受保護方法

protected boolean checkLayoutParams (ViewGroup.LayoutParams p)

         (譯者注:檢測是不是AbsoluteLayout.LayoutParams的實例)

 

protected LinearLayout.LayoutParams generateDefaultLayoutParams ()

返回寬度為MATCH_PARENT, 高度為WRAP_CONTENT的布局參數集合。

                   返回值

默認布局參數集合或空

 

protected LinearLayout.LayoutParams generateLayoutParams (ViewGroup.LayoutParams p)

基於提供的布局參數返回一組安全的布局參數集合.當傳入 ViewGroup 的視圖的參數沒有通過checkLayoutParams(android.view.ViewGroup.LayoutParams) 的檢測時,調用該方法. 該方法會返回適合 ViewGroup 的新的布局參數,可能從指定的布局參數中復制適當的屬性。

                   參數

p      要轉換為適合於 ViewGroup 的布局參數的集合

                   返回值

                       ViewGroup.LayoutParams或其子類的實例

 

protected void onLayout (boolean changed, int l, int t, int r, int b)

該視圖設置其子視圖的大小及位置時調用.派生類可以重寫此方法,並為其子類布局。

                   參數

changed           是否為視圖設置了新的大小和位置

l       相對於父視圖的左側的位置

t      相對於父視圖的頂部的位置

r      相對於父視圖的右側的位置

b      相對於父視圖的底部的位置

 

protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)

評估視圖及其內容,以決定其寬度和高度.此方法由measure(int, int) 調用,子類可以重載以提供更精確、更有效率的衡量其內容尺寸的方法。

約定: 覆蓋該方法時,必須調用 setMeasuredDimension(int, int) 方法來保存評估結果的視圖的寬度和高度.如果忘記將導致 measure(int, int) 方法拋出IllegalStateException異常.要有效的利用父類的onMeasure(int, int)方法。

基類測量的是背景的大小,除非 MeasureSpec 允許超過背景.子類應該重寫 onMeasure(int, int) 方法,以為其內容提供更適合的大小。

如果重寫了該方法,子類要確保其高度和寬度大於等於視圖的最小高度和寬度. (getSuggestedMinimumHeight()getSuggestedMinimumWidth()

                   參數

widthMeasureSpec         父視圖要求的橫向空間大小.該要求由 View.MeasureSpec 進行了編碼處理。

heightMeasureSpec        父視圖要求的縱向空間大小.該要求由 View.MeasureSpec 進行了編碼處理。

 

 

13.3 TableLayout常用的屬性

android:collapseColumns:以第0行為序,隱藏指定的列:

android:collapseColumns該屬性為空時,如下圖:

 

把android:collapseColumns=0,2--------------》意思是把第0和第2列去掉,如下圖:

 

android:shrinkColumns:以第0行為序,自動延伸指定的列填充可用部分:

當LayoutRow里面的控件還沒有布滿布局時,shrinkColumns不起作用,如下圖:

 

設置了shrinkColumns=0,1,2,布局完全沒有改變,因為LayoutRow里面還剩足夠的空間。

當LayoutRow布滿控件時,如下圖:

 

設置設置了shrinkColumns=2,則結果如下圖,控件自動向垂直方向填充空間:

 

android:stretchColumns:以第0行為序,盡量把指定的列填充空白部分:

 

設置stretchColumns=1,則結果如下圖,第1列被盡量填充(Button02與TextView02同時向右填充,直到TextView03被壓擠到最后邊)。

 

 

 

13.4 TableLayout的使用

如果現在我們要實現下圖所示的布局效果 :

 

 

我們要在XML文件中作如下的相關聲明和設置:

<TableLayout android:id="@+id/TableLayout01"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

xmlns:android="http://schemas.android.com/apk/res/android">

<TableRow android:id="@+id/TableRow01"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content">

        <TextView android:id="@+id/label"

               android:layout_height="wrap_content"

               android:layout_width="160dip"

               android:gravity="right"

               android:text="用戶名:"

               android:padding="3dip" >

        </TextView>

<EditText android:id="@+id/entry"

               android:layout_height="wrap_content"

               android:layout_width="160dip“

               android:padding="3dip" >

        </EditText>

</TableRow>

 

<TableRow android:id="@+id/TableRow02"

       android:layout_width="wrap_content"

        android:layout_height="wrap_content">

        <Button android:id="@+id/ok"

               android:layout_height="wrap_content"

               android:padding="3dip"

               android:text="確認">

        </Button>

<Button android:id="@+id/Button02"

               android:layout_width="wrap_content"

               android:layout_height="wrap_content"

               android:padding="3dip"

               android:text="取消">

        </Button>

</TableRow>

   </TableLayout>

 

14 RelativeLayout相對布局

14.1 RelativeLayout類的層次關系

相對布局(RelativeLayout)是一種非常靈活的布局方式,能夠通過指定界面元素與其他元素的相對位置關系,確定界面中所有元素的布局位置

特點:能夠最大程度保證在各種屏幕類型的手機上正確顯示界面布局。它的層次關系如下所示:

java.lang.Object

 android.view.View

   android.widget.ViewGroup

     android.widget.RelativeLayout

14.2 RelativeLayout常用的方法

方法

功能描述

返回值

RelativeLayout

兩個構造函數:

RelativeLayout(Contex contex)

RelativeLayout(Contex contex,AttributeSet attrs

null

checkLayoutParams(viewGroup.LayoutParams p

檢查參數指定的布局參數是否是LayoutParams實例

boolen

isBaselineAligned()

判斷布局是否按照基線對齊

boolean

set BaselineAligned(boolean baseelineAligned)

根據參數設置基線對齊

void

setGravityt (int gravity)

根據指定的重力設置元素大小

void

setHorizontalGravity(int gravity)

設置水平方向的重力

void

setVerticalGravity(int gravity)

設置垂直方向的重力

void

gennerateDefaultLayoutParams

生成默認的布局參數實例

ViewGroup.LayoutParams

 

14.3 RelativeLayout常用的屬性

android:layout_above        將該控件的底部至於給定ID的控件之上

android:layout_below        將該控件的頂部至於給定ID的控件之下

android:layout_toLeftOf      將該控件的右邊緣和給定ID的控件的左邊緣對齊

android:layout_toRightOf     將該控件的左邊緣和給定ID的控件的右邊緣對齊android:layout_alignBaseline 該控件的baseline和給定ID的控件的baseline對齊

android:layout_alignBottom     將該控件的底部邊緣與給定ID控件的底部邊緣

android:layout_alignLeft     將該控件的左邊緣與給定ID控件的左邊緣對齊

android:layout_alignRight      將該控件的右邊緣與給定ID控件的右邊緣對齊

android:layout_alignTop      將給定控件的頂部邊緣與給定ID控件的頂部對齊

android:alignParentBottom    如果該值為true,則將該控件的底部和父控件的底部對齊

android:layout_alignParentLeft      如果該值為true,則將該控件的左邊與父控件的左邊對齊

android:layout_alignParentRight    如果該值為true,則將該控件的右邊與父控件的右邊對齊

android:layout_alignParentTop      如果該值為true,則將空間的頂部與父控件的頂齊

android:layout_centerHorizontal    如果值為真,該控件將被至於水平方向的中央

android:layout_centerInParent      如果值為真,該控件將被至於父控件水平方向和垂直方向的中央

android:layout_centerVertical        如果值為真,該控件將被至於垂直方向的中央

 

14.4 RelativeLayout的使用

 

 

比如要實現上面的布局效果,我們需要在 在xml中做如下的聲明:

<RelativeLayout android:id="@+id/RelativeLayout01"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

xmlns:android="http://schemas.android.com/apk/res/android">

<TextView android:id="@+id/label"

        android:layout_height="wrap_content"

        android:layout_width="fill_parent"

        android:text="用戶名:">

</TextView>

<EditText android:id="@+id/entry"

        android:layout_height="wrap_content"

        android:layout_width="fill_parent"

android:layout_below="@id/label"> //確定EditText控件在IDlabel的元素下方

 

</EditText>

  <Button android:id="@+id/cancel"

      android:layout_height="wrap_content"

        android:layout_width="wrap_content"

android:layout_alignParentRight="true"  //聲明該元素在其父元素的右邊邊界對齊

              android:layout_marginLeft="10dip" //左移10dip

        android:layout_below="@id/entry"

        android:text="取消" >

</Button>

<Button android:id="@+id/ok"

        android:layout_height="wrap_content"

        android:layout_width="wrap_content"

              android:layout_toLeftOf="@id/cancel" //聲明該元素在IDcancel元素的左邊

              android:layout_alignTop="@id/cancel“ //聲明該元素與IDcancel的元素在相同的水平位置

 

        android:text=“確認”>

</Button>

</RelativeLayout>

 

 

 

 

 

 

 

15 AbsoluteLayout絕對布局

15.1 AbsoluteLayout層次關系

絕對布局(AbsoluteLayout)能通過指定界面元素的坐標位置,來確定用戶界面的整體布局

絕對布局是一種不推薦使用的界面布局,因為通過X軸和Y軸確定界面元素位置后,Android系統不能夠根據不同屏幕對界面元素的位置進行調整,降低了界面布局對不同類型和尺寸屏幕的適應能力。

同其他布局一樣,android.widget.AbsoluteLayout是android.view.ViewGroup類的子類,其層次關系如下:

java.lang.Object

  android.view.View

android.widget.ViewGroup

  android.widget.AbsoluteLayout

 

15.2 AbsoluteLayout常用的方法

方法

功能描述

返回值

AbsoluteLayout

提供了3個構造函數

null

checkLayoutParams(ViewGroup.LayoutParams p)

檢查參數指定的布局參數是否是LayoutParams實例

 

onLayout(boolean changed,int l,int t,int r,int b)

視圖的布局改變時,該方法被調用

boolean

setBaselineAligned(boolean baseelineAligned)

根據參數設置基線對齊

boolen

onMeasure(int widthMesureSpec, int h)

該方法被measure調用,用於測量視圖的高度和寬度

void

setHorizontalGravity(int gravity)

設置水平方向是的重力

void

 

15.3 AbsoluteLayout常用屬性

對與AbsoluteLayout標簽,最主要的兩個參數是

android:layout_x  指定X坐標的位置

android:layout_y  指定Y坐標的位置

 

AbsoluteLayout常用的屬性有:

第一類:屬性值為true或false
android:layout_centerHrizontal                                           水平居中
android:layout_centerVertical                                            垂直居中
android:layout_centerInparent                                           相對於父元素完全居中
android:layout_alignParentBottom                                     貼緊父元素的下邊緣
android:layout_alignParentLeft                                          貼緊父元素的左邊緣
android:layout_alignParentRight                                        貼緊父元素的右邊緣
android:layout_alignParentTop                                          貼緊父元素的上邊緣
android:layout_alignWithParentIfMissing                            如果對應的兄弟元素找不到的話就以父元素做參照物

第二類:屬性值必須為id的引用名“@id/id-name”
android:layout_below                          在某元素的下方
android:layout_above                          在某元素的的上方
android:layout_toLeftOf                       在某元素的左邊
android:layout_toRightOf                     在某元素的右邊

android:layout_alignTop                      本元素的上邊緣和某元素的的上邊緣對齊
android:layout_alignLeft                      本元素的左邊緣和某元素的的左邊緣對齊
android:layout_alignBottom                 本元素的下邊緣和某元素的的下邊緣對齊
android:layout_alignRight                    本元素的右邊緣和某元素的的右邊緣對齊

第三類:屬性值為具體的像素值,如30dip,40px
android:layout_marginBottom              離某元素底邊緣的距離
android:layout_marginLeft                   離某元素左邊緣的距離
android:layout_marginRight                 離某元素右邊緣的距離
android:layout_marginTop                   離某元素上邊緣的距離

 

15.4 AbsoluteLayout的使用

 

 

要實現上圖所示的效果,我們可以在XML布局聲明如下:

<AbsoluteLayout android:id="@+id/AbsoluteLayout01"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

xmlns:android="http://schemas.android.com/apk/res/android">

<TextView android:id="@+id/label"

        android:layout_x="40dip"

        android:layout_y="40dip"

        android:layout_height="wrap_content"

        android:layout_width="wrap_content"

        android:text="用戶名:">

</TextView>

<EditText android:id="@+id/entry"

        android:layout_x="40dip"

        android:layout_y="60dip"

android:layout_height="wrap_content" 8.                               android:layout_width="150dip">

        </EditText>

       <Button android:id="@+id/ok"

                 android:layout_width="70dip"

          android:layout_height="wrap_content"   

             android:layout_x="40dip"

                android:layout_y="120dip" 

                android:text="確認">

       </Button>

    <Button android:id="@+id/cancel"

                 android:layout_width="70dip"

              android:layout_height="wrap_content"

                 android:layout_x="120dip"

              android:layout_y="120dip"       

              android:text="取消">

</Button>

   </AbsoluteLayout>

 

15.5 補充

文章連接:

      我的Android學習之旅[6]——以示例程序來展示Android的幾種布局方式

                第六講:用戶界面 View(二)

                如何動態改變 AbsoluteLayout布局中其它布局的坐標

 

 

 

 

16 Menu菜單

16.1 Menu的介紹

菜單是應用程序中非常重要的組成部分,能夠在不占用界面空間的前提下,為應用程序提供了統一的功能和設置界面,並為程序開發人員提供了易於使用的編程接口

Android系統支持三種菜單

選項菜單(Option Menu)

子菜單(Submenu)

上下文菜單(Context Menu)

 

16.2選項菜單的介紹以及使用

選項菜單是一種經常被使用的Android系統菜單

打開方式:通過“菜單鍵”(MENU key)打開

選項菜單分類:

圖標菜單(Icon Menu)

擴展菜單(Expanded Menu)

(1)圖標菜單能夠同時顯示文字和圖標的菜單,最多支持6個子項

圖標菜單不支持單選框和復選框

 

 

(2)擴展菜單是在圖標菜單子項多余6個時才出現,通過點擊圖標菜單最后的子項“More”才能打開

擴展菜單是垂直的列表型菜單

不能夠顯示圖標

支持單選框和復選框

 

 

下面我們就要來實現選項菜單的功能:

 

 

16.3子菜單的介紹以及使用

子菜單是能夠顯示更加詳細信息的菜單子項

菜單子項使用了浮動窗體的顯示形式,能夠更好適應小屏幕的顯示方式

 

子菜單不支持嵌套

子菜單的添加是使用addSubMenu()函數實現

 

 

16.4上下文菜單的介紹以及使用

快捷菜單同樣采用了動窗體的顯示方式,與子菜單的實現方式相同,但兩種菜單的啟動方式卻截然不同

啟動方式:快捷菜單類似於普通桌面程序中的“右鍵菜單”,當用戶點擊界面元素超過2秒后,將啟動注冊到該界面元素的快捷菜單

使用方法:與使用選項菜單的方法非常相似,需要重載onCreateContextMenu()函數和onContextItemSelected()函數

onCreateContextMenu()函數主要用來添加快捷菜單所顯示的標題、圖標和菜單子項等內容

 

上下文菜單常用的方法:

setHeaderIcon(int iconRes) 設置上下文菜單的圖標

setHeaderIcon(Drawable icon) 上下文菜單的圖標

setHeaderTitle(Charsequence title) 設置上下文菜單的標題

setHeaderTitle(int titleRes)設置上下文菜單的標題

add(int groupId,int itemId,int order, CharSequence title) 使用add方法添加 子菜單:

groupId:組Id

itemId:菜單項Id

order :順序號

title :菜單項標題

 

 

17 AutoCompleteTextView自動提示

17.1 AutoCompleteTextView類層次關系

AutoCompleteTextView控件是用戶在文本框中輸入的時候,在控件下方會顯示一個類似 百度的下拉提示框,提示當前與輸入相匹配的選項,用戶可以直接選擇,方便了用戶的直接體驗。

 

 

 

AutoCompleteTextView類的層次關系如下:

java.lang.Object

android.view.view

android.view.TextView

android.widget.EditText

android.widget. AutoCompleteTextView

 

17.2 AutoCompleteTextView常用的方法

方法

功能描述

返回值

setMarqueeRepeatLimit

在指定的marquee的情況下,設置重復滾動的次數,當設置為marquee_forever時表示無限次

void

enoughToFilter

當文本長度超過閥值時過濾

boolean(true/False)

performValidation

確定文本中單個符號的有效性

void

setTokenzier

設置分詞組件,該組件決定用戶正在輸入文本的范圍

void

performFiltering

過濾從函數findTokenStart()到函數getSelectionEnd()獲得的長度為0或者超過了預定值的文本內容

void

replaceText

根據參數的文本替換從函數findTokenStart()到函數getSelectionEnd()獲得的文本

void

 

17.3 AutoCompleteTextView的實現

AutoCompleteTextView在XML中的聲明方式如下:

<AutoCompleteTextView

  android:id="@+id/AutoCompleteTextView01"

  android:layout_width="fill_parent"

  android:layout_height="wrap_content"

  >

  </AutoCompleteTextView>

  <MultiAutoCompleteTextView

  android:id="@+id/MultiAutoCompleteTextView01"

  android:layout_width="fill_parent"

  android:layout_height="wrap_content"

  >

  </MultiAutoCompleteTextView>

AutoCompleteTextView在代碼中的實現步驟:

      //關聯關鍵字

       ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,

               android.R.layout.simple_dropdown_item_1line, autoString);

       

       AutoCompleteTextView m_AutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.AutoCompleteTextView01);

       

       //將adapter添加到AutoCompleteTextView中

       m_AutoCompleteTextView.setAdapter(adapter);

       ///////////////////

       MultiAutoCompleteTextView mm_AutoCompleteTextView = (MultiAutoCompleteTextView) findViewById(R.id.MultiAutoCompleteTextView01);

       //將adapter添加到AutoCompleteTextView中

       mm_AutoCompleteTextView.setAdapter(adapter);

       mm_AutoCompleteTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());

 

17.4補充

補充

相關文章鏈接

Android控件之AutoCompleteTextView、MultiAutoCompleteTextView探究

AutoCompleteTextView和MultiAutoCompleteTextView

Auto Complete Text

 

18 DatePicker日期

18.1 DatePicker的類層次關系

DatePicker日期選擇器是一個選擇年月日的日歷布局視圖,它的類層次關系如下:

 public class DatePicker extends FrameLayout

 

java.lang.Object

android.view.View

       android.view.ViewGroup

              android.widget.FrameLayout

                     android.widget.DatePicker

 

                                  

18.2 DatePicker的常用方法

公共方法

         (1)public int getDayOfMonth ()

         獲取選擇的天數

 

         (2)public int getMonth ()

         獲取選擇的月份。(注意:返回數值為0..11,需要自己+1來顯示)

 

        (3) public int getYear ()

         獲取選擇的年份

 

         (4)public void init (int year, int monthOfYear, int dayOfMonth, DatePicker.OnDateChangedListener onDateChangedListener)

         初始化狀態。(初始化年月日)

                   參數:

                            year :        初始年(注意使用new Date()初始化年時,需要+1900,如下:date.getYear() + 1900

                            monthOfYear: 初始月。

                            dayOfMonth:   初始日。

                            onDateChangedListener:         日期改變時通知用戶的事件監聽,可以為空(null)。

 

         (5)public void setEnabled (boolean enabled)

         設置視圖的啟用狀態。該啟用狀態隨子類的不同而有不同的解釋。

                   參數

                            enabled True if this view is enabled, false otherwise.設置為true表示啟動視圖,反之禁用。

 

         (6)public void updateDate (int year, int monthOfYear, int dayOfMonth)

         更新日期

 

受保護方法

         (7)protected void dispatchRestoreInstanceState (SparseArray<Parcelable> container)

         重寫使我們能夠完全控制這小部件的保存或恢復。(譯者注:此處直接調用了父類的ViewGroup. dispatchThawSelfOnly方法)

                   參數

                            container         SparseArray 持有保存以前的狀態。The SparseArray which holds previously saved state.

 

         (8)protected void onRestoreInstanceState (Parcelable state)

         允許視圖重新應用以前通過onSaveInstanceState()生成代表內部的狀態。這個函數決不調用一個空的狀態。

                   參數

                            state  返回以前調用onSaveInstanceState()保存下來的狀態。

 

        (9) protected Parcelable onSaveInstanceState ()

         允許視圖生成一個代表內部的狀態,以后可用於創建一個與之相同的新的實例。這種狀態應該只包含非持久或以后不能夠重建的信息。例如,你決不存儲你當前在屏幕上的位置,因為這會在視圖的層面上重新計算放置一個新的實例。

         你可以存儲到這里的一些例子:一個文本框中當前光標的位置(但通常不是文字本身,文字通常保存在內容提供者(content provider)或其他持久的儲存中),一個列表視圖中的當前選中項。

                   返回值

                            返回一個包含視圖當前狀態的Parcelable對象,或沒有什么狀態保存時返回null。默認實現返回null。

 

18.3 DatePicker的使用

首先在XML中聲明一個DatePicker,和一個用戶顯示監聽結果的TextView:

<DatePicker android:id="@+id/datePicker1"

   android:layout_height="wrap_content"

   android:layout_width="wrap_content"></DatePicker>

   <TextView

   android:id="@+id/textview1"

    android:layout_height="wrap_content"

    android:text="@string/hello"

android:layout_width="wrap_content"/>

 

然后在Activity中顯示DatePicker並實現監聽事件

textview = (TextView)findViewById(R.id.textview1);

        datepicker = (DatePicker)findViewById(R.id.datePicker1);

        //獲取當前時間

        calendar = Calendar.getInstance();

        //顯示當前的時間

        textview.setText("當前時間:"+calendar.get(Calendar.YEAR)+"年"

             +(calendar.get(Calendar.MONTH)+1)+"月"+calendar.get(Calendar.DAY_OF_MONTH)+"日");

       

        //注冊監聽事件,當日期改變時,更新TextView的內容

        datepicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {

       

        @Override

        public void onDateChanged(DatePicker view, int year, int monthOfYear,

              int dayOfMonth) {

           // TODO Auto-generated method stub

           textview.setText("當前時間:"+year+"年"

                   +(monthOfYear+1)+"月"+dayOfMonth+"日");

        }

      });

效果如下顯示:

 

 

 

 

19 TimePicker時間選擇器

19.1 Timepicker類的層次關系

TimePicker時間選擇器是用於選擇一天中時間的視圖,TimePicker類層次關系如下:

public class TimePicker extends FrameLayout

 

java.lang.Object

android.view.View

     android.view.ViewGroup

              android.widget.FrameLayout

                     android.widget.TimePicker

 

19.2 TimePicker類常用的方法

公共方法

         (1)public int getBaseline ()

         返回窗口空間的文本基准線到其頂邊界的偏移量。如果這個部件不支持基准線對齊,這個方法返回-1/。

                   返回值

基准線的偏移量,如果不支持基准線對齊則返回-1。

 

        (2) public Integer getCurrentHour ()

         獲取當前時間的小時部分。

                   返回值

                            當前小時(0-23)

 

         (3)public Integer getCurrentMinute ()

         獲取當前時間的分鍾部分。

                   返回值

                            當前分鍾。

 

         (4)public boolean is24HourView ()

         獲取當前系統設置是否是24小時制。

                   返回值

                            如果是24小時制返回true,否則返回false。

 

         (5)public void setCurrentHour (Integer currentHour)

    設置當前小時。

 

         (6)public void setCurrentMinute (Integer currentMinute)

         設置當前分鍾(0-59)。

 

         (7)public void setEnabled (boolean enabled)

    設置可用的視圖狀態。可用的視圖狀態的解釋在子類中改變。

                   參數

                            enabled  如果可用為true,否則為false。

 

         (8)public void setIs24HourView (Boolean is24HourView)

    設置是24小時還是上午/下午制。

                   參數

                            is24HourView     True表示 24小時制. False表示上午/下午制.

 

         (9)public void setOnTimeChangedListener (TimePicker.OnTimeChangedListener onTimeChangedListener)

         設置時間調整事件的回調函數。

                   參數

                            onTimeChangedListener                   回調函數,不能為空。

 

受保護方法

         (10)protected void onRestoreInstanceState (Parcelable state)

         允許一個視圖回復到之前用onSaveInstanceState()保存的狀態,state參數不能為空。

                   參數

                            state     之前調用onSaveInstanceState()返回的狀態。

 

         (11)protected Parcelable onSaveInstanceState ()

        

         用來允許一個視圖保存當前的內部狀態,之后可以創建新的實例應用相同的狀態。狀態信息不能包含常量或在之后重新構造。例如,你永遠不能保存在屏幕上的當前位置,因為當創建一個新的視圖時,它將會被放置到它的層次結構中,它的位置會被重新計算。

         你可以存儲到這里的一些例子:一個文本框中當前光標的位置(但通常不是文字本身,文字通常保存在內容提供者(content provider)或其他持久的儲存中),一個列表視圖中的當前選中項。

                   返回值

           返回一個包含視圖當前狀態的Parcelable對象,或沒有什么狀態保存時返回null。默認實現返回null。

 

19.3 TimePicker的使用實例

TimePicker和DatePicker的使用一樣:

XML中:

<TimePicker android:id="@+id/timePicker1"

   android:layout_width="wrap_content" android:layout_height="wrap_content"></TimePicker>

   

<TextView

    android:id="@+id/textview1" 

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:text="@string/hello"

/>

 

然后在 Activity中顯示TimePicker並實現監聽:

imepicker = (TimePicker)findViewById(R.id.timePicker1);

        textview  =(TextView)findViewById(R.id.textview1);

      //獲取當前時間

        calendar = Calendar.getInstance();

        //顯示當前的時間

        textview.setText("當前時間:"+calendar.get(Calendar.HOUR)+"時"

             +calendar.get(Calendar.MINUTE)+"分");

       

        //注冊監聽事件,當時間改變時,更新TextView的內容

        timepicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {

       

        @Override

        public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {

           // TODO Auto-generated method stub

           textview.setText("當前時間:"+hourOfDay+"時"

                   +minute+"分");

        }

      });

19.4 補充

補充

      文章鏈接

     [示例代碼]Hello, TimePicker

     [示例代碼]日期選擇器(DatePicker)和時間選擇器(TimePicker)

      Android TimePicker DatePicker 簡單說明

 

 

 

20 Dialog對話框

20.1 Dialog對話框

Android中實現對話框可以使用AlterDialog.Builder類,還可以自定義對話框。如果對話框設置了按鈕,那么就需要對其設置監聽OnClickListener。

 

20.2Dialog的使用

首先在Dialog.xml中定義一個對話框,我們這里定義一個包含兩個TextView和兩個EditView的對話框

Dialog.xml中的布局如下:

<TextView

        android:id="@+id/username"

        android:layout_height="wrap_content"

        android:layout_width="wrap_content"

        android:layout_marginLeft="20dip"

        android:layout_marginRight="20dip"

        android:text="賬號"

        android:gravity="left"

        android:textAppearance="?android:attr/textAppearanceMedium" />

           

    <EditText

        android:id="@+id/username"

        android:layout_height="wrap_content"

        android:layout_width="fill_parent"

        android:layout_marginLeft="20dip"

        android:layout_marginRight="20dip"

        android:scrollHorizontally="true"

        android:autoText="false"

        android:capitalize="none"

        android:gravity="fill_horizontal"

        android:textAppearance="?android:attr/textAppearanceMedium" />

 

    <TextView

        android:id="@+id/password"

        android:layout_height="wrap_content"

        android:layout_width="wrap_content"

        android:layout_marginLeft="20dip"

        android:layout_marginRight="20dip"

        android:text="密碼"

        android:gravity="left"

        android:textAppearance="?android:attr/textAppearanceMedium" />

           

    <EditText

        android:id="@+id/password"

        android:layout_height="wrap_content"

        android:layout_width="fill_parent"

        android:layout_marginLeft="20dip"

        android:layout_marginRight="20dip"

        android:scrollHorizontally="true"

        android:autoText="false"

        android:capitalize="none"

        android:gravity="fill_horizontal"

        android:password="true"

        android:textAppearance="?android:attr/textAppearanceMedium" />

 

 

 

 

main.xml布局中:

  

<TextView 

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:text="@string/hello"

    />

 

然后在Activity中使用AlterDialog創建對話框:

Dialog dialog = new AlertDialog.Builder(DialogActivity.this)

        .setTitle("登陸提示")//設置標題

        .setMessage("這里需要登錄!")//設置內容

        .setPositiveButton("確定",//設置確定按鈕

        new DialogInterface.OnClickListener()

        {

           public void onClick(DialogInterface dialog, int whichButton)

           {

              //點擊“確定”轉向登陸框

             

              LayoutInflater factory = LayoutInflater.from(DialogActivity.this);

              //得到自定義對話框

                   final View DialogView = factory.inflate(R.layout.dialog, null);

                   //創建對話框

                   AlertDialog dlg = new AlertDialog.Builder(DialogActivity.this)

                   .setTitle("登錄框")

                   .setView(DialogView)//設置自定義對話框的樣式

                   .setPositiveButton("確定", //設置"確定"按鈕

                   new DialogInterface.OnClickListener() //設置事件監聽

                   {

                       public void onClick(DialogInterface dialog, int whichButton)

                       {

                       //輸入完成后,點擊“確定”開始登陸

                       m_Dialog = ProgressDialog.show

                                      (

                                      DialogActivity.this,

                                        "請等待...",

                                        "正在為你登錄...",

                                        true

                                      );

                          

                           new Thread()

                           {

                             public void run()

                             {

                               try

                               {

                                 sleep(3000);

                               }

                               catch (Exception e)

                               {

                                 e.printStackTrace();

                               }

                               finally

                               {

                                  //登錄結束,取消m_Dialog對話框

                                  m_Dialog.dismiss();

                               }

                             }

                           }.start();

                       }

                   })

                   .setNegativeButton("取消", //設置“取消”按鈕

                   new DialogInterface.OnClickListener()

                   {

                       public void onClick(DialogInterface dialog, int whichButton)

                       {

                       //點擊"取消"按鈕之后退出程序

                       DialogActivity.this.finish();

                       }

                   })

                   .create();//創建

                   dlg.show();//顯示

           }

        }).setNeutralButton("退出",

        new DialogInterface.OnClickListener()

        {

        public void onClick(DialogInterface dialog, int whichButton)

        {

           //點擊"退出"按鈕之后推出程序

           DialogActivity.this.finish();

        }

      }).create();//創建按鈕

 

      // 顯示對話框

      dialog.show();

 

實現的效果圖:

 

21 ImageView圖片視圖

21.1 ImageView類的結構

ImageView顯示任意圖像,例如圖標。ImageView類可以加載各種來源的圖片(如資源或圖片庫),需要計算圖像的尺寸,比便它可以在其他布局中使用,並提供例如縮放和着色(渲染)各種顯示選項。

繼承關系

public class View.OnClickListner extends View

 

java.lang.Object

android.view.View

android.widget.ImageView

 

直接子類

ImageButton, QuickContactBadge 

 

間接子類

ZoomButton

 

21.2 ImageView類屬性

 

XML屬性

屬性名稱

描述

android:adjustViewBounds

設置該屬性為真可以在 ImageView 調整邊界時保持圖片的縱橫比例。(譯者注:需要與maxWidth、MaxHeight一起使用,否則單獨使用沒有效果。)

android:baseline

視圖內基線的偏移量

android:baselineAlignBottom

如果為true,圖像視圖將基線與父控件底部邊緣對齊。

android:cropToPadding

如果為真,會剪切圖片以適應內邊距的大小。(譯者注:是否截取指定區域用空白代替。單獨設置無效果,需要與scrollY一起使用,效果如下,實現代碼見代碼部分:

android:maxHeight

為視圖提供最大高度的可選參數。(譯者注:單獨使用無效,需要與setAdjustViewBounds一起使用。如果想設置圖片固定大小,又想保持圖片寬高比,需要如下設置:

1)  設置setAdjustViewBounds為true;

2)  設置maxWidth、MaxHeight;

3)  設置layout_width和layout_height為wrap_content。)

android:maxWidth

為視圖提供最大寬度的可選參數。

android:scaleType

控制為了使圖片適合 ImageView 的大小,應該如何變更圖片大小或移動圖片。一定是下列常量之一:

常量

描述

matrix

0

用矩陣來繪圖

fitXY

1

拉伸圖片(不按比例)以填充View的寬高

 

fitStart

2

按比例拉伸圖片,拉伸后圖片的高度為View的高度,且顯示在View的左邊

 

fitCenter

3

按比例拉伸圖片,拉伸后圖片的高度為View的高度,且顯示在View的中間

 

fitEnd

4

按比例拉伸圖片,拉伸后圖片的高度為View的高度,且顯示在View的右邊

 

center

5

按原圖大小顯示圖片,但圖片寬高大於View的寬高時,截圖圖片中間部分顯示

 

centerCrop

6

按比例放大原圖直至等於某邊View的寬高顯示。

 

centerInside

7

當原圖寬高或等於View的寬高時,按原圖大小居中顯示;反之將原圖縮放至View的寬高居中顯示。

 

(譯者注:設置圖片的填充方式。)

android:src

設置可繪制對象作為 ImageView 顯示的內容

android:tint

為圖片設置着色顏色。(譯者注:將圖片渲染成指定的顏色。見下圖:

左邊為原圖,右邊為設置后的效果,見后面代碼。)

 

21.3 ImageView常用的方法

公共方法

(1)public final void clearColorFilter ()

(譯者注:清除顏色過濾,參見這里

 

         (2)public int getBaseline ()

         返回部件頂端到文本基線的偏移量。如果小部件不支持基線對齊,該方法返回 -1。

                   返回值

                            小部件頂端到文本基線的偏移量;或者是 -1 當小部件不支持基線對齊時。

 

         (3)public boolean getBaselineAlignBottom ()

         返回當前視圖基線是否將考慮視圖的底部。

                   參見

                            setBaselineAlignBottom(boolean)

 

         (4)public Drawable getDrawable ()

         返回視圖的可繪制對象;如果沒有關聯可繪制對象,返回空。

 

         (5)public Matrix getImageMatrix ()

         返回視圖的選項矩陣。當繪制時,應用於視圖的可繪制對象。如果沒有矩陣, 函數返回空。不要更改這個矩陣。如果你要為可繪制對象設置不同的矩陣, 請調用 setImageMatrix()。

 

         (6)public ImageView.ScaleType getScaleType ()

返回當前 ImageView 使用的縮放類型。

相關 XML 屬性

             android:scaleType

參見

               ImageView.ScaleType

 

         (7)public void invalidateDrawable (Drawable dr)

使指定的可繪制對象失效。

參數

dr    要設為失效的可繪制對象。

 

         (8)public void jumpDrawablesToCurrentState ()

調用與視圖相關的所有可繪制對象的Drawable.jumpToCurrentState()方法。

 

         (9)public int[] onCreateDrawableState (int extraSpace)

為當前視圖生成新的 Drawable 狀態時發生。當視圖系統檢測到緩存的可繪制對象失效時,調用該方法.你可以使用 getDrawableState() 方法重新取得當前的狀態。

參數

extraSpace      如果為非零,該值為你要在返回值的數組中存放的你自己的狀態信息的數量。

返回值

返回保存了視圖的當前 Drawable 狀態的數組。

 

         (10)public void setAdjustViewBounds (boolean adjustViewBounds)

當你需要在 ImageView 調整邊框時保持可繪制對象的比例時,將該值設為真。

參數

adjustViewBounds          是否調整邊框,以保持可繪制對象的原始比例。

相關 XML 屬性

             android:adjustViewBounds

 

(11)public void setAlpha (int alpha)

(譯者注:設置透明度)

 

(12)public void setBaseline (int baseline)

         設置部件頂部邊界文本基線的偏移量。這個值覆蓋setBaselineAlignBottom(boolean)設置的屬性值。

參數

baseline 使用的基線,或不提供設置為-1。

相關 XML屬性

               android:baseline

參見

             setBaseline(int)

 

(13)public void setBaselineAlignBottom (boolean aligned)

設置是否設置視圖底部的視圖基線。設置這個值覆蓋setBaseline()的所有調用。

參數

aligned    如果為true,圖像視圖將基線與父控件底部邊緣對齊。

相關 XML屬性

             android:baselineAlignBottom

 

(14)public final void setColorFilter (int color)

為圖片設置着色選項。采用SRC_ATOP合成模式。

參數

color        應用的着色顏色。

相關 XML 屬性

    android:tint

 

(15)public void setColorFilter (ColorFilter cf)

為圖片應用任意顏色濾鏡。

參數

cf     要應用的顏色濾鏡(可能為空)

 

(16)public final void setColorFilter (int color, PorterDuff.Mode mode)

為圖片設置着色選項。

參數

color        應用的着色顏色。

mode       如何着色。標准模式為 SRC_ATOP。

相關 XML 屬性

    android:tint

 

         (17)public void setImageBitmap (Bitmap bm)

設置位圖作為該 ImageView 的內容。

參數

bm 設置的位圖。

 

         (18)public void setImageDrawable (Drawable drawable)

設置可繪制對象為該 ImageView 顯示的內容。

參數

drawable         設置的可繪制對象。

 

         (19)public void setImageLevel (int level)

設置圖片的等級,當圖片來自於 LevelListDrawable 時。(譯者注:使用參見這里

參數

level         圖片的新的等級。

 

(20)public void setImageMatrix (Matrix matrix)

         (譯者注:矩陣變換)

 

        (21) public void setImageResource (int resId)

通過資源ID設置可繪制對象為該 ImageView 顯示的內容。

注意:該操作讀取位圖,並在 UI 線程中解碼,因此可能導致反應遲緩。 如果反應遲緩,可以考慮用 setImageDrawable(Drawable)、 setImageBitmap(Bitmap) 或者 BitmapFactory 代替。

參數

resId        可繪制對象的資源標識。

相關 XML 屬性

               android:src

 

         (21)public void setImageState (int[] state, boolean merge)

         (譯者注:設置視圖的可見和不可見,使用參見這里

 

         (22)public void setImageURI (Uri uri)

設置指定的 URI 為該 ImageView 顯示的內容。

注意:該操作讀取位圖,並在 UI 線程中解碼,因此可能導致反應遲緩。 如果反應遲緩,可以考慮用 setImageDrawable(Drawable)、 setImageBitmap(Bitmap) 或者 BitmapFactory 代替。

參數

uri   圖像的 URI。

 

(23)public void setMaxHeight (int maxHeight)

用於設置該視圖支持的最大高度的可選參數。只有 setAdjustViewBounds(boolean) 為真時有效。要設置圖像最大尺寸為 100×100,並保持原始比率,做法如下:

1)         設置 adjustViewBounds 為真;

2)         設置 maxWidth 和 maxHeight 為 100;

3)         設置寬、高的布局參數為 WRAP_CONTENT。

注意,如果原始圖像較小,即使設置了該參數,圖像仍然要比 100×100 小。如果要設置圖片為 固定大小,需要在布局參數中指定大小,並使用 setScaleType(ImageView.ScaleType) 函數來檢測,如何 將其調整到適當的大小。

參數

maxHeight      該視圖的最大高度。

相關 XML 屬性

    android:maxHeight

 

         (24)public void setMaxWidth (int maxWidth)

用於設置該視圖支持的最大寬度的可選參數。只有 setAdjustViewBounds(boolean) 為真時有效。要設置圖像最大尺寸為 100×100,並保持原始比率,做法如下:

4)         設置 adjustViewBounds 為真;

5)         設置 maxWidth 和 maxHeight 為 100;

6)         設置寬、高的布局參數為 WRAP_CONTENT。

注意,如果原始圖像較小,即使設置了該參數,圖像仍然要比 100×100 小。如果要設置圖片為 固定大小,需要在布局參數中指定大小,並使用 setScaleType(ImageView.ScaleType) 函數來檢測,如何 將其調整到適當的大小。

參數

maxWidth       該視圖的最大寬度。

相關 XML 屬性

                            android:maxWidth

 

(25)public void setScaleType (ImageView.ScaleType scaleType)

控制圖像應該如何縮放和移動,以使圖像與 ImageView 一致。

參數

scaleType        需要的縮放方式。

相關 XML 屬性

    android:scaleType

 

(26)public void setSelected (boolean selected)

改變視圖的選中狀態。視圖有選中和未選中兩個狀態。注意,選擇狀態不同於焦點。 典型的選中的視圖是象 ListView 和 GridView 這樣的 AdapterView 中顯示的 內容;選中的內容會顯示為高亮。

參數

selected           為真,將視圖設為選中狀態;否則為假。

 

受保護方法

(27)protected void drawableStateChanged ()

在視圖狀態的變化影響到所顯示可繪制對象的狀態時調用該方法。

覆蓋該方法時,要確保調用了父類的該方法。

 

(28)protected void onDraw (Canvas canvas)

實現該方法,用於自己繪制內容。

參數

canvas    用於繪制背景的畫布。

 

(29)protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)

評估視圖及其內容,以決定其寬度和高度.此方法由 measure(int, int) 調用,子類可以重載以提供更精確、更有效率的衡量其內容尺寸的方法。

約定: 覆蓋該方法時,必須調用 setMeasuredDimension(int, int) 方法來保存評估結果的視圖的寬度和高度.如果忘記將導致 measure(int, int) 方法拋出IllegalStateException異常。要有效的利用父類的 onMeasure(int, int)方法。

基類測量的是背景的大小,除非 MeasureSpec 允許超過背景.子類應該重寫 onMeasure(int, int) 方法,以為其內容提供更適合的大小。

如果重寫了該方法,子類要確保其高度和寬度大於等於視圖的最小高度和寬度. (getSuggestedMinimumHeight() 和 getSuggestedMinimumWidth())

參數

widthMeasureSpec         父視圖要求的橫向空間大小.該要求由 View.MeasureSpec 進行了編碼處理。

heightMeasureSpec        父視圖要求的縱向空間大小.該要求由 View.MeasureSpec 進行了編碼處理。

 

(30)protected boolean onSetAlpha (int alpha)

透明度改變時執行。子類可以使用該方法指定透明度值,然后返回真; 在調用 onDraw() 時,使用該透明度值。如果返回假,則先在不可見的緩存中繪制視圖, 完成該請求;看起來不錯,但是可能相對於在子類中繪制要慢。默認實現返回假。

參數

alpha       應用到視圖的透明度值 (0…255)。

返回值

    如果該類可以繪制該阿爾法值返回真。

 

(31)protected boolean setFrame (int l, int t, int r, int b)

為視圖指定大小和位置。 該方法有布局調用。

參數

l       左側位置,相對於父容器。

t      頂部位置,相對於父容器。

r      右側位置,相對於父容器。

b      底部位置,相對於父容器。

返回值

             true 如果新的大小和位置與之前的不同,返回真。

 

(32)protected boolean verifyDrawable (Drawable dr)

如果你的視圖子類顯示自己的可繪制對象,他應該重寫此方法並為自己的每個可繪制對象返回真。該函數允許為這些可繪制對象准備動畫效果。

重寫此方法時,要保證調用其父類的該方法。

參數

dr    待校驗的可繪制對象.如果是你顯示的對象之一,返回真;否則返回調用父類的返回值。

返回值

boolean 如果可繪制對象已經顯示在視圖上了,返回真;否則返回假,不允許動畫效果。

 

 

 

 

21.4 ImageView的使用

如果現在我們要顯示一張圖片,並動態更新它的透明度alpha,效果如下圖所示

 

則我們首先要在XML文件中聲明一個ImageView和一個TextView :

<ImageView

    android:id="@+id/ImageView01"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    >

</ImageView>

<TextView

    android:id="@+id/TextView01"

    android:layout_below="@id/ImageView01"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    >

</TextView>

 

 

然后在Activity中設置顯示ImageView:

isrung     = true;

      

       //獲得ImageView的對象

       imageview = (ImageView) this.findViewById(R.id.ImageView01);

       textview = (TextView) this.findViewById(R.id.TextView01);

      

       //設置imageview的圖片資源。同樣可以再xml布局中像下面這樣寫

       //android:src="@drawable/logo"

       imageview.setImageResource(R.drawable.imag2);

      

       //設置imageview的Alpha值

       imageview.setAlpha(image_alpha);

 

之后就需要用一個線程來實時更新alpha:

//開啟一個線程來讓Alpha值遞減

       new Thread(new Runnable() {

           public void run()

           {

              while (isrung)

              {

                  try

                  {

 

                     Thread.sleep(200);

                     //更新Alpha值

                     updateAlpha();

                  }

                  catch (InterruptedException e)

                  {

                     e.printStackTrace();

                  }

              }

 

           }

       }).start();

 

       //接受消息之后更新imageview視圖

       mHandler = new Handler() {

           @Override

           public void handleMessage(Message msg)

           {

              super.handleMessage(msg);

              imageview.setAlpha(image_alpha);

              textview.setText("現在alpha值是:"+Integer.toString(image_alpha));

              //更新

              imageview.invalidate();

           }

       };

    }

   

    public void updateAlpha()

    {

       if (image_alpha - 7 >= 0)

       {

           image_alpha -= 7;

       }

       else

       {

           image_alpha = 0;

           isrung = false;

       }

       //發送需要更新imageview視圖的消息

       mHandler.sendMessage(mHandler.obtainMessage());

    }

21.5 補充

補充

         文章精選

                   Android ImageView 加邊框

                   Android用ImageView顯示本地和網上的圖片

                   imageView動畫效果

 

22 Gallery拖動效果

22. 1 Gallery類的層次關系

Gallery是一個鎖定中心條目並且擁有水平滾動列表的視圖。

Gallery(畫廊)使用Theme_galleryItemBackground作為Gallery(畫廊)適配器中的各視圖的默認參數。如果你沒有設置,你就需要調整一些Gallery(畫廊)的屬性,比如間距。

Gallery(畫廊)中的視圖應該使用Gallery.LayoutParams作為它們的布局參數類型。

參見Gallery tutorial

 

內部類

class                   Gallery.LayoutParams

Gallery(畫廊)擴展了LayoutParams,以此提供可以容納當前的轉換信息和先前的位置轉換信息的場所。

Galery是一個實現圖片拖動的非常炫的一個效果,Gallery類的層次關系如下:

結構

繼承關系

         public class Gallery extends AbsSpinner

implements GestureDetector.OnGestureListener

 

java.lang.Object

   android.view.View

           android.view.ViewGroup

                   android.widget.AdapterView<T extends android.widget.Adapter>

                           android.widget.AbsSpinner

                                   android.widget.Gallery

22.2 Gallery的XML 屬性

 XML屬性

 

屬性名稱

描述

android:animationDuration

設置布局變化時動畫的轉換所需的時間(毫秒級)。僅在動畫開始時計時。該值必須是整數,比如:100。

android:gravity

 指定在對象的X和Y軸上如何放置內容。指定一下常量中的一個或多個(使用 “|”分割)

Constant

Value

Description

top

0x30

緊靠容器頂端,不改變其大小

bottom

0x50

緊靠容器底部,不改變其大小

left

0x03

緊靠容器左側,不改變其大小

right

0x05

緊靠容器右側,不改變其大小

center_vertical

0x10

垂直居中,不改變其大小

fill_vertical

0x70

垂直方向上拉伸至充滿容器

center_horizontal

0x01

水平居中,不改變其大小

Fill_horizontal

0x07

水平方向上拉伸使其充滿容器

center

0x11

居中對齊,不改變其大小

fill

0x77

在水平和垂直方向上拉伸,使其充滿容器

clip_vertical

0x80

垂直剪切(當對象邊緣超出容器的時候,將上下邊緣超出的部分剪切掉)

clip_horizontal

0x08

水平剪切(當對象邊緣超出容器的時候,將左右邊緣超出的部分剪切掉)

 

android:spacing

(譯者注:設置圖片之間的間距)

android:unselectedAlpha

 設置未選中的條目的透明度(Alpha)。該值必須是float類型,比如:“1.2”。

 

 

22.3 Gallery類的常用方法

公共方法

(1)public boolean dispatchKeyEvent (KeyEvent event)

         在焦點路徑上分發按鈕事件到下一個視圖。該路徑從視圖樹的頂端遍歷到當前獲得焦點的視圖。如果當前視圖已獲得焦點,就分發給自身。否則,就分發到下一個節點的焦點路徑上。該方法監聽任何按鈕事件。

參數

                            event        被分發的按鈕事件

                   返回值

                            boolean    時間被處理返回true,否則false

 

(2)public void dispatchSetSelected (boolean selected)

分發setSelected給視圖的子類。

參數

selected   新選中的狀態

 

(4)public ViewGroup.LayoutParams generateLayoutParams (AttributeSet attrs)

返回一個新的已設置屬性集合的布局參數。

參數

attrs                   用於生成布局參數的屬性集合

返回值

一個ViewGroup.LayoutParams實例或者它的子類

        

(5)public boolean onDown (MotionEvent e)

當輕擊和按下手勢事件發生時通知該方法。任何按下事件都會直接觸發該方法。所有其他的事件都要先於該方法。

參數

e       按下動作事件

 

(6)public boolean onFling (MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)

當初始化的按下動作事件和松開動作事件匹配時通知fling(譯者注:快滑,用戶按下觸摸屏、快速移動后松開)事件。該動作的速度通過計算X和Y軸上每秒移動多少像素得來。

參數

e1     導致開始fling的按下動作事件。

e2     觸發當前onFling方法的移動動作事件

velocityX  測量fling沿X軸上的速度,像素/每秒

velocityY  測量fling沿Y軸上的速度,像素/每秒

返回值

如果該事件被消耗返回true,否則false。

 

(7)public boolean onKeyDown (int keyCode, KeyEvent event)

處理左,右和點擊事件

參數

keyCode   代表按下按鈕的按鍵碼,來自KeyEvent

event        定義按鈕動作的KeyEvent對象。

返回值

如果已經處理了按鈕事件,則返回true。如果你想讓下一個事件接收者處理,就返回false

參見

onKeyDown(int, KeyEvent)

 

(8)public boolean onKeyUp (int keyCode, KeyEvent event)

KeyEvent.Callback.onKeyMultiple()方法的默認實現:當KEYCODE_DPAD_CENTER 或者 KEYCODE_ENTER被釋放時,執行點擊視圖操作。

參數

keyCode   代表按下按鈕的按鍵碼,來自KeyEvent

event        定義按鈕動作的KeyEvent對象。

返回值

如果已經處理了按鈕事件,則返回true。如果你想讓下一個事件接收者處理,就返回false

 

(9)public void onLongPress (MotionEvent e)

MotionEvent初始化並按下觸發長按並通知本方法

參數

e       導致開始長按的初始按下動作事件。

 

 

(10)public boolean onScroll (MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)

當初始按下動作事件和當前移動動作事件導致滾動時通知本方法。為了方便提供了X和Y軸上的距離。

監聽屏幕滾動事件。為了方便提供了X和Y軸上的距離。

參數

e1   導致滾動開始按下的動作事件。

e2   觸發當前onScroll方法的移動動作事件。

distanceX        距離是自上一次調用onScroll方法在X軸上的距離。不是e1 和e2之間的距離。

distanceY        距離是自上一次調用onScroll方法在Y軸上的距離。不是e1 和e2之間的距離。

返回值

如果該事件被消耗返回true否則false

 

(11)public void onShowPress (MotionEvent e)

用戶已經執行按下動作還沒有執行移動或者彈起動作。該事件常通過高亮一個元素來向用戶提供一個視覺反饋即用戶的操作已經被辨識了。

參數

e       按下動作事件

 

(12)public boolean onSingleTapUp (MotionEvent e)

在輕擊動作和up動作事件觸發時通知本方法。(譯者注:點擊屏幕上的某項的執行流程  有兩種情況,一種是時間很短,一種時間稍長:時間很短:onDown--->onSingleTapUp--->onSingleTapConfirmed,見這里1這里2。)

參數

e       完成開始輕擊的up動作事件

返回值

如果該事件被消耗返回true否則false

 

(13)public boolean onTouchEvent (MotionEvent event)

實現該方法來處理觸摸屏動作事件

參數

event        動作事件

返回值

如果該事件被消耗返回true否則false

 

(14)public void setAnimationDuration (int animationDurationMillis)

設置當子視圖改變位置時動畫轉換時間。僅限於動畫開始時生效。

參數

animationDurationMillis          動畫轉換時間(毫秒級)

        

(15)public void setCallbackDuringFling (boolean shouldCallback)

當flinged時是否回調每一個getOnItemSelectedListener()。如果設為false,只回調最終選中的項。如果為true,則所有的項都會回調。

參數

shouldCallback         設置拋滑的過程中是否回調

 

(16)public void setGravity (int gravity)

描述子視圖的對齊方式。

 

(17)public void setSpacing (int spacing)

設置Gallery中項的間距

參數

spacing    Gallery中項的間距,以像素為單位

 

(18)public void setUnselectedAlpha (float unselectedAlpha)

設置Gallery中未選中項的透明度(alpha)值。

參數

unselectedAlpha      未選中項的透明度(alpha)值

 

(19)public boolean showContextMenu ()

顯示該視圖上下文菜單。

返回值

上下文菜單是否顯示。

 

(20)public boolean showContextMenuForChild (View originalView)

為指定的視圖或者其父類顯示上下文菜單。

大部分情況下,子類不需要重寫該方法。但是,如果子類被直接添加到窗口管理器(例如:addView(View.android.view.ViewGroup.LayoutParams)),此時就需要重寫來顯示上下文菜單

參數

originalView    上下文菜單初次調用的源視圖

返回值

如果上下文菜單被顯示了 則返回true。

 

受保護方法

(21)protected int computeHorizontalScrollExtent ()

在水平范圍內計算滾動條滑塊的滾動范圍。該值用來計算滾動條滑塊的長度。

該范圍可以使用任意的單位但是必須跟computeHorizontalScrollRange()computeHorizontalScrollOffset()的單位保持一致。

默認范圍是視圖的寬度。

返回值

滾動條滑塊的水平滾動范圍

 

(22)protected int computeHorizontalScrollOffset ()

在水平范圍內計算滾動條滑塊的偏移量。該值用來計算水平滑塊的位置。

該范圍可以使用任意的單位但是必須跟computeHorizontalScrollRange()computeHorizontalScrollExtent()的單位保持一致。

默認偏移量是視圖的偏移量。

返回值

滾動條滑塊的水平偏移量。

 

(23)protected int computeHorizontalScrollRange ()

計算滾動條水平方向上的滾動范圍。

該范圍可以使用任意的單位但是必須跟computeHorizontalScrollExtent()computeHorizontalScrollOffset()的單位保持一致。

返回值

水平滾動條代表的滑動總范圍。

 

(24)protected void dispatchSetPressed (boolean pressed)

分發 setPressed到View的子類。

參數

                            pressed    新按下的狀態

 

(25)protected ViewGroup.LayoutParams generateDefaultLayoutParams ()

返回默認的布局參數。當View作為參數傳遞給addView(View)而沒有布局參數時就會請求這些參數。如果返回null,則addView會拋出異常。

返回值

默認的布局參數或null

 

(26)protected ViewGroup.LayoutParams generateLayoutParams (ViewGroup.LayoutParams p)

返回一組合法的受支持的布局參數。當把ViewGroup傳遞給View而該View的布局參數並沒有通過checkLayoutParams(android.view.ViewGroup.LayoutParams)的測試時,就會調用該方法。該方法應該返回一組適合該ViewGroup的新的布局參數,該過程可能需要從指定的一組布局參數中復制相關的屬性。

參數

p       被轉換成適合該ViewGroup的一組參數。

返回值

返回一個ViewGroup.LayoutParams的實例或者一個它的子類。

 

(27)protected int getChildDrawingOrder (int childCount, int i)

返回迭代的繪制子類索引。如果你想改變子類的繪制順序就要重寫該方法。默認返回 i 值。

提示:為了能夠調用該方法,你必須首先調用setChildrenDrawingOrderEnabled(boolean)來允許子類排序。

參數

         childCount        子類個數

i        當前迭代順序

返回值

繪制該迭代子類的索引

 

(28)protected boolean getChildStaticTransformation (View child, Transformation t)

(譯者注:setStaticTransformationsEnabled這個屬性設成true的時候每次viewGroup(看Gallery的源碼就可以看到它是從ViewGroup間接繼承過來的)在重新畫它的child的時候都會促發getChildStaticTransformation這個函數。這里1這里2

 

(29)protected ContextMenu.ContextMenuInfo getContextMenuInfo ()

Views如果有額外的信息跟上下文菜單有聯系的話就需要實現該方法。返回的結果被用作回調方法onCreateContextMenu(ContextMenu, View, ContextMenuInfo)的參數。

返回值

顯示上下文菜單的條目的額外信息。這些信息將會改變View不同的子類

 

(30)protected void onFocusChanged (boolean gainFocus, int direction, Rect previouslyFocusedRect)

當該視圖的焦點狀態發生改變時將會調用視圖系統。當導向的方向觸發焦點事件時,方向和先前獲得焦點的矩形提供焦點事件的來源。當用戶重寫該方法,必須調用父類方法來觸發標准的焦點處理事件。

參數

gainFocus                   如果View獲得焦點為true,否則false

direction         當調用requestFocus()方法來給該視圖焦點時焦點的移動方向。該值:FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT 或 FOCUS_RIGHT。該參數不常用,通常使用它的默認值。

previouslyFocusedRect    該視圖坐標系統中先前獲得焦點的視圖的矩形。如果適用,這將獲得焦點事件來源的更細致的信息(除了方向以外)。否則為null。

 

(31)protected void onLayout (boolean changed, int l, int t, int r, int b)

當視圖為每一個子類分配大小和位置時從布局中調用該方法。有子類的派生類應該重寫該方法在子類中調用布局。

參數

changed   該視圖新的大小和位置。

l        相對父容器的左側位置

t        相對父容器的頂部位置

r        相對父容器的右側位置

b       相對父容器的底部位置

 

22.4 Gallery的使用

在XML中聲明一個Gallery:

main.xml

           <?xml version="1.0" encoding="utf-8"?>

<Gallery xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gallery"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:gravity="center_vertical"

        android:background="?android:galleryItemBackground"

        />

然后需要聲明一個存放圖片的容器ImageAdapter,之后就可以通過setAdapter方法把資源添加到Gallery中來顯示,並設置好監聽事件處理:

 

        gallery = (Gallery)findViewById(R.id.gallery);

       gallery.setAdapter(new ImageAdapter(this));//設置圖片適配器

        //設置監聽器

        gallery.setOnItemClickListener(new OnItemClickListener() {

         @Override

         public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,  long arg3) {

            Toast.makeText(MyGallery.this, "點擊了第"+arg2+"張圖片", Toast.LENGTH_LONG).show();

         }

     });

    }

}

 

 聲明一個存放圖片的容器ImageAdapter:

 

class ImageAdapter extends BaseAdapter{

  private Context context;

  //圖片源數組

  private Integer[] imageInteger={

         R.drawable.gallery_photo_1,

         R.drawable.gallery_photo_2,

         R.drawable.gallery_photo_3,

         R.drawable.gallery_photo_4,

         R.drawable.gallery_photo_5,

         R.drawable.gallery_photo_6,

         R.drawable.gallery_photo_7,

         R.drawable.gallery_photo_8

  };

  public ImageAdapter(Context c){

     context = c;

  }

  @Override

  public int getCount() {

     return imageInteger.length;

  }

  @Override

  public Object getItem(int position) {

     return position;

  }

  @Override

  public long getItemId(int position) {

     // TODO Auto-generated method stub

     return position;

  }

  @Override

  public View getView(int position, View convertView, ViewGroup parent) {

     ImageView imageView = new ImageView(context);

     imageView.setImageResource(imageInteger[position]);

     imageView.setScaleType(ImageView.ScaleType.FIT_XY);

     imageView.setLayoutParams(new Gallery.LayoutParams(136, 88));

     return imageView;

  }}

 

22.5 補充

補充

文章精選

         Android開發——使用Gallery實現“多級聯動”

         android 圖片拖動效果(Gallery)

 

23 ImageSwitcher切換圖片

23.1 ImageSwitcher類概述

ImageSwitcher是Android中控制圖片展示效果的一個控件,如:幻燈片效果...,頗有感覺啊,做相冊一絕。

 

ImageSwitcher類的層次關系如下:

public class ImageSwitcher extends ViewSwitcher

 

java.lang.Object

android.view.View

     android.view.ViewGroup

    android.widget.FrameLayout

     android.widget.ViewAnimator

      android.widget.ViewSwitcher                        android.widget.ImageSwitcher

 

23.2 ImageSwitcher常用的方法

方法

功能描述

返回值

ImageSwitcher

兩個構造方法:

ImageSwitcher(Context contex)

ImageSwitcher(Contex contex,AttributeSet attrs)

null

setImageDrawable(Drawable drawable)

設置圖片為參數drawable指定的資源

void

setImageResource(int resid)

設置圖片為參數resid所指定的資源。resid是編譯器為資源生成唯一標識,例如R.id.pcil

void

setInAnimation(Context context,in id)

設置圖片進入屏幕時所顯示的動畫

void

setOutAnimation(Context context,in id)

設置圖片退出屏幕時,所顯示的動畫

void

setImageURI(Uri uri)

設置圖片為參數uri(例如一個圖片的web鏈接)所指定的資源

void

addView(View child,int index,ViewGroup.LayoutParams params)

繼承自ViewSwitcher的方法,用於添加視圖。child是要添加的視圖,params是視圖的布局

View

getNextView()

繼承自ViewSwitcher的方法,用於獲取視圖

 

getCurrentView()

繼承自ViewAnimator的方法,用於獲取視圖

View

getDisplayedChild();

當前顯示的子視圖的索引

int

removeAllViews()

繼承在ViewAnimator的方法,用於移除所有的子視圖

void

removeViewAt(int index)

繼承自ViewAnimator的方法,用於移除index所指定的視圖

void

setAnimateFirstView(boolean animate)

繼承自ViewAnimator的方法,用於設置視圖是否在首次顯示時播放動畫

void

removeViews(int start,int count)

繼承自ViewAnimator的方法,用於移除自start的count個子視圖

void

showNext()

繼承自ViewAnimator的方法,由於顯示下一張圖片

void

  

 

23.3 ImageSwitcher的使用

我們直接在Activity中實現,繼承監聽OnClickListenner和ViewFactory接口:
public class ImageSwitcherActivity extends Activity implements OnClickListener,ViewFactory

/* 所有要顯示的圖片資源索引 */

    private static final Integer[] imagelist =

    {

       R.drawable.img1,

       R.drawable.img2,

       R.drawable.img3,

       R.drawable.img4,

       R.drawable.img5,

       R.drawable.img6,

       R.drawable.img7,

       R.drawable.img8,

    };

   

    //創建ImageSwitcher對象

    private ImageSwitcher           m_Switcher;

    //索引

    private static int              index         = 0;

 

    //“下一頁”按鈕ID

    private static final int    BUTTON_DWON_ID    = 0x123456;

    //“上一頁”按鈕ID

    private static final int    BUTTON_UP_ID  = 0x123457;

    //ImageSwitcher對象的ID

    private static final int    SWITCHER_ID       = 0x123458;

 

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState)

    {

       super.onCreate(savedInstanceState);

 

       //創建一個線性布局LinearLayout

       LinearLayout main_view = new LinearLayout(this);

       //創建ImageSwitcher對象

       m_Switcher = new ImageSwitcher(this);

       //在線性布局中添加ImageSwitcher視圖

       main_view.addView(m_Switcher);

       //設置ImageSwitcher對象的ID

       m_Switcher.setId(SWITCHER_ID);

       //設置ImageSwitcher對象的數據源

       m_Switcher.setFactory(this);

       m_Switcher.setImageResource(imagelist[index]);

      

       //設置顯示上面創建的線性布局

       setContentView(main_view);

 

       //創建“下一張”按鈕

       Button next = new Button(this);

       next.setId(BUTTON_DWON_ID);

       next.setText("下一張");

       next.setOnClickListener(this);

       LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(100, 100);

       main_view.addView(next, param);

 

       //創建“上一張”按鈕

       Button pre = new Button(this);

       pre.setId(BUTTON_UP_ID);

       pre.setText("上一張");

       pre.setOnClickListener(this);

       main_view.addView(pre, param);

 

    }

 

    //事件監聽、處理

    public void onClick(View v)

    {

       switch (v.getId())

       {

           //下一頁

           case BUTTON_DWON_ID:

               index++;

              if (index >= imagelist.length)

              {

                  index = 0;

              }

              //ImageSwitcher對象資源索引

              m_Switcher.setImageResource(imagelist[index]);

              break;

           //上一頁

           case BUTTON_UP_ID:

              index--;

              if (index < 0)

              {

                  index = imagelist.length - 1;

              }

              //ImageSwitcher對象資源索引

              m_Switcher.setImageResource(imagelist[index]);

              break;

           default:

              break;

       }

    }

 

    public View makeView()

    {

       //將所有圖片通過ImageView來顯示

       return new ImageView(this);

    }

實現的效果如下所示:

 

23.4 補充資料

補充

         文章鏈接

                   Android ImageSwitcher

                   Image Switcher View | Android Developer Tutorial

 

24 GridView網絡視圖

24.1 GridView類概述

GridView是一個在平面上可顯示多個條目的可滾動的視圖組件,該組件中的條目通過一個ListAdapter和該組件進行關聯。比如android手機中顯示的應用:

 

GridView類的層次關系如下:

public final class GridView extends AbsListView

 

java.lang.Object

android.view.View

    android.view.ViewGroup

android.widget.AdapterView<T extends android.widget.Adapter>

                android.widget.AbsListView

                    android.widget.GridView

24.2 GridView常用屬性

XML屬性

屬性名稱

描述

android:columnWidth

設置列的寬度。關聯的方法為:setColumnWidth(int)

android:gravity

設置此組件中的內容在組件中的位置。可選的值有:top、bottom、left、right、center_vertical、fill_vertical、center_horizontal、fill_horizontal、center、fill、clip_vertical 可以多選,用“|”分開。關聯方法:setGravity (int gravity)

android:horizontalSpacing

兩列之間的間距。關聯方法:setHorizontalSpacing(int)

android:numColumns

列數。關聯方法:setNumColumns(int)

android:stretchMode

縮放模式。關聯方法:setStretchMode(int)

android:verticalSpacing

兩行之間的間距。關聯方法:setVerticalSpacing(int)

 

24.3 GridView常用的方法

構造函數

         (1)public GridView (Context context)

         創建一個默認屬性的GridView實例

public GridView (Context context, AttributeSet attrs)

創建一個帶有attrs屬性的GridView實例

(2)public GridView (Context context, AttributeSet attrs, int defStyle)

創建一個帶有attrs屬性,並且指定其默認樣式的GridView實例

公共方法

         (3)public ListAdapter getAdapter ()

獲得與此組件相關的適配器..

返回值

    ListAdapter適配器實例

        

         (4)public int getStretchMode ()

獲得GridView的縮放模式..

 

         (5)public boolean onKeyDown (int keyCode, KeyEvent event)

默認由KeyEvent.Callback.onKeyMultiple()實現,如果視圖是可用的並且是可點擊的,那么傳入KEYCODE_DPAD_CENTER或KEYCODE_ENTER值是執行的是按下視圖操作。

       參數

              keyCode  一個表示按下操作的鍵值.

event  表示按鈕事件的對象. 

                  返回值

如果你認為已經完成事件處理,不想讓讓下一個處理器來處理此事件,則返回true,否則返回false。

 

         (6)public boolean onKeyMultiple (int keyCode, int repeatCount, KeyEvent event)

默認由KeyEvent.Callback.onKeyMultiple()實現,總是返回false(不處理此事件)。

         參數

                   keyCode  鍵值.

repeatCount  該動作發生的次數.

event  事件對象. 

                  返回值

如果你認為已經完成事件處理,不想讓讓下一個處理器來處理此事件,則返回true,否則返回false。

 

         (7)public boolean onKeyUp (int keyCode, KeyEvent event)

默認由KeyEvent.Callback.onKeyMultiple()實現,如果視圖是可用的並且是可點擊的,那么傳入KEYCODE_DPAD_CENTER或KEYCODE_ENTER值是執行的是點擊視圖操作。

參數

              keyCode  鍵值.

event  事件對象.

                  返回值

如果你認為已經完成事件處理,不想讓讓下一個處理器來處理此事件,則返回true,否則返回false。

 

         (8)public void setAdapter (ListAdapter adapter)

設置GridView的數據。

                  參數

                            adapter  為grid提供數據的適配器 

 

         (9)public void setColumnWidth (int columnWidth)

設置GridView的列寬.

                  參數

                            columnWidth  列的寬度,以像素為單位

 

         (10)public void setGravity (int gravity)

設置控件內容的位置,默認值為:Gravity.LEFT.

                  參數

                            gravity  位置值

 

         (11)public void setHorizontalSpacing (int horizontalSpacing)

設置列間距.

                  參數

                            horizontalSpacing  列間距值

 

(12)public void setNumColumns (int numColumns)

         設置grid的列數

參數

numColumns  列數值.

 

(13)public void setSelection (int position)

         設置選中的條目.

參數

position  數據條目在列表中的索引值(從0開始),如果在可觸摸的模式下,在該索引值下的條目將不會被選中,但是該索引值仍然指向該條目。

 

(14)public void setStretchMode (int stretchMode)

設置grid中的條目以什么縮放模式去填充空間。.

參數

stretchMode  可選值:NO_STRETCH,STRETCH_SPACING,STRETCH_SPACING_UNIFORM,或STRETCH_COLUMN_WIDTH

 

(15)public void setVerticalSpacing (int verticalSpacing)

設置行間距.

參數

verticalSpacing  間距值,以像素為單位..

 

24.4 GridView的簡單使用

現在要實現如下圖所示的效果:

 

我們聲明兩個xml文件,一個是gridview.xml 聲明一個GridView:

gridview.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

   android:layout_width="wrap_content"

   android:layout_height="wrap_content">

   <GridView android:id="@+id/mygridview"

      android:numColumns="3"

      android:gravity="center_horizontal"

      android:layout_width="wrap_content"

      android:layout_height="wrap_content">

   </GridView>

</LinearLayout>

 

一個是Grid_item.xml,包含要顯示的一個ImageView和一個TextView

grid_item.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout android:id="@+id/RelativeLayout01"

   android:layout_width="fill_parent" android:layout_height="fill_parent"

   xmlns:android="http://schemas.android.com/apk/res/android">

   <ImageView android:id="@+id/image_item"

      android:layout_width="wrap_content"

      android:layout_height="wrap_content">

   </ImageView>

   <TextView android:id="@+id/text_item"

      android:layout_below="@+id/image_item"

      android:layout_height="wrap_content"

      android:layout_width="wrap_content">

   </TextView>

</RelativeLayout>

 

然后在Activity 中就可以實現顯示了:

 

//准備要添加的數據條目

      List<Map<String, Object>> items = new ArrayList<Map<String,Object>>();

      for (int i = 0; i < 10; i++) {

        Map<String, Object> item = new HashMap<String, Object>();

        item.put("imageItem", R.drawable.icon);

        item.put("textItem", "text" + i);

        items.add(item);

      }

//實例化一個適配器

      SimpleAdapter adapter = new SimpleAdapter(this, items, R.layout.grid_item, new String[]{"imageItem", "textItem"}, new int[]{R.id.image_item, R.id.text_item});

      //獲得GridView實例

      gridview = (GridView)findViewById(R.id.mygridview);

      //gridview.setNumColumns(3);//可以在xml中設置

      //gridview.setGravity(Gravity.CENTER);//同上

//將GridView和數據適配器關聯

      gridview.setAdapter(adapter);

 

25 ScrollView卷軸視圖

25.1 ScrollView類概述

ScrollView是一種可供用戶滾動的層次結構布局容器,允許顯示比實際多的內容。ScrollView是一種FrameLayout,意味需要在其上放置有自己滾動內容的子元素。子元素可以是一個復雜的對象的布局管理器。通常用的子元素是垂直方向的LinearLayout,顯示在最上層的垂直方向可以讓用戶滾動的箭頭。

TextView類也有自己的滾動功能,所以不需要使用ScrollView,但是只有兩個結合使用,才能保證顯示較多內容時候的效率。但只有兩者結合使用才可以實現在一個較大的容器中一個文本視圖效果。

ScrollView只支持垂直方向的滾動。

ScrollView類的結構如下:

繼承關系

public class ScrollView extends FrameLayout

        

java.lang.Object

android.view.View

         android.view.ViewGroup

                   android.widget.FrameLayout

                            android.widget.ScrollView

 

25.2 ScrollView常用的方法

構造函數

(1)public ScrollView (Context context)

創建一個默認屬性的ScrollView實例。

 

(2)public ScrollView (Context context, AttributeSet attrs)

創建一個帶有attrs屬性的ScrollView 實例。

 

(3)public ScrollView (Context context, AttributeSet attrs, int defStyle)

創建一個帶有attrs屬性,並且指定其默認樣式的ScrollView實例。

 

公共方法

(4)public void addView (View child)

       添加子視圖。如果事先沒有給子視圖設置layout參數,會采用當前ViewGroup的默認參數來設置子視圖。

              參數

                     child       所添加的子視圖

 

(5)public void addView (View child, int index)

添加子視圖。如果事先沒有給子視圖設置layout參數,會采用當前ViewGroup的默認參數來設置子視圖。

參數

child       所添加的子視圖

             index      添加子視圖的位置

        

(6)public void addView (View child, int index, ViewGroup.LayoutParams params)

根據指定的layout參數添加子視圖

參數

             child       所添加的子視圖

             index      添加子視圖的位置

             params   為子視圖設置的layout參數

 

(7)public void addView (View child, ViewGroup.LayoutParams params)

根據指定的layout參數添加子視圖。

參數

             child       所添加的子視圖

             params   為子視圖設置的layout參數

 

(8)public boolean arrowScroll (int direction)

響應點擊上下箭頭時對滾動條滾動的處理。

              參數

                     direction        按下的箭頭所對應的方向

返回值

如果我們處理(消耗)了此事件返回true,否則返回false。

 

(9) public void computeScroll ()

被父視圖調用,用於必要時候對其子視圖的值(mScrollX和mScrollY)進行更新。典型的情況如:父視圖中某個子視圖使用一個Scroller對象來實現滾動操作,會使得此方法被調用。

 

(10)public boolean dispatchKeyEvent (KeyEvent event)

       發送一個key事件給當前焦點路徑的下一個視圖。此焦點路徑從視圖樹的頂層執行直到當前焦點視圖。如果此視圖為焦點視圖,將為自己發送。否則,會為當前焦點路徑的下一個節點發送。此方法也會激起一個key監聽器。

參數

                     event     發送的key事件

返回值

事件被處理返回true,否則返回false。

 

(11)public void draw (Canvas canvas)

手動繪制視圖(及其子視圖)到指定的畫布(Canvas)。這個視圖必須在調用這個函數之前做好了整體布局。當實現一個視圖時,不需要繼承這個方法;相反,你應該實現onDraw(Canvas)方法。

參數

canvas    繪制視圖的畫布

 

(12)public boolean executeKeyEvent (KeyEvent event)

當接收到key事件時,用戶可以調用此函數來使滾動視圖執行滾動,類似於處理由視圖體系發送的事件。

參數

event     需要執行key的事件

返回值

事件被處理返回true,否則返回false。

 

(13)public void fling (int velocityY)

滾動視圖的滑動(fling)手勢。(譯者注: 如何監聽android的屏幕滑動停止事件

參數

                     velocityY      Y方向的初始速率。正值表示手指/光標向屏幕下方滑動,而內容將向上滾動。

 

(14)public boolean fullScroll (int direction)

對響應“home/end”短按時響應滾動處理。此方法將視圖滾動到頂部或者底部,並且將焦點置於新的可視區域的最頂部/最底部組件。若沒有適合的組件做焦點,當前的ScrollView會收回焦點。

參數

direction滾動方向:FOCUS_UP表示視圖向上滾動;FOCUS_DOWN表示視圖向下滾動

返回值

若key事件被消耗(consumed)返回true,其他情況返回false。

 

(15)public int getMaxScrollAmount ()

返回值

當前滾動視圖響應箭頭事件能夠滾動的最大數。

 

(16)public boolean isFillViewport ()

指示當前ScrollView的內容是否被拉伸以填充視圖可視范圍(譯者注:viewport可視范圍,參見決定Scrollviewer里面Control的可視范圍)。

返回值

內容填充視圖返回true,否則返回false。

 

(17)public boolean isSmoothScrollingEnabled ()

返回值

             按箭頭方向滾動時,是否顯示滾動的平滑效果。

 

(18)public boolean onInterceptTouchEvent (MotionEvent ev)

實現此方法是為了攔截所有觸摸屏幕時的運動事件。可以像處理發送給子視圖的事件一樣去監視這些事件,並且獲取當前手勢在任意點的ownership

使用此方法時候需要注意,因為它與View.onTouchEvent(MotionEvent)有相當復雜的交互,並且前提需要正確執行View.onTouchEvent(MotionEvent)。事件將按照如下順序接收到:

1.    收到down事件

2.    Down事件或者由視圖組的一個子視圖處理,或者被用戶自己的onTouchEvent()方法處理;此處理意味你應該執行onTouchEvent()時返回true,這樣才能繼續看到剩下的手勢(取代找一個父視圖處理)。如果onTouchEvent()返回true時,你不會收到onInterceptTouchEvent()的任何事件並且所有對觸摸的處理必須在onTouchEvent()中發生。

3.    如果此方法返回false,接下來的事件(up to and including the final up)將最先被傳遞當此,然后是目標的onTouchEvent()。

4.    如果返回true,將不會收到以下任何事件:目標view將收到同樣的事件但是會伴隨ACTION_CANCEL,並且所有的更進一步的事件將會傳遞到你自己的onTouchEvent()方法中而不會再在這里出現。

參數

             ev          體系向下發送的動作事件

返回值

如果將運動事件從子視圖中截獲並且通過onTouchEvent()發送到當前ViewGroup ,返回true。當前目標將會收到ACTION_CANCEL事件,並且不再會有其他消息傳遞到此。

              (譯者注:onInterceptTouchEvent和onTouchEvent調用時序

 

(19)public boolean onTouchEvent (MotionEvent ev)

執行此方法為了處理觸摸屏幕的運動事件。

參數

     ev          運動事件

返回值

事件被處理返回true,其它返回false。

 

(20)public boolean pageScroll (int direction)

響應短按“page up/ down”時候對滾動的處理。此方法將向上或者向下滾動一屏,並且將焦點置於新可視區域的最上/最下。如果沒有適合的component作為焦點,當前scrollView將收回焦點。

參數

     direction        滾動方向:FOCUS_UP表示向上翻一頁,FOCUS_DOWN表示向下翻一頁。

返回值

此key事件被消耗(cosumed)返回true,其他返回false。

 

(21)public void requestChildFocus (View child, View focused)

當父視圖的一個子視圖的要獲得焦點時,調用此方法。

參數

     child              要獲得焦點的父視圖的子視圖。此視圖包含了焦點視圖。如果沒有特殊徐要求,此視圖實際上就是焦點視圖。

              focused        子視圖的子孫視圖並且此子孫視圖是真正的焦點視圖

 

(22)public boolean requestChildRectangleOnScreen (View child, Rect rectangle, boolean immediate)

當組里的某個子視圖需要被定位在屏幕的某個矩形范圍時,調用此方法。重載此方法的ViewGroup可確認以下幾點:

    * 子項目將是組里的直系子項

    * 矩形將在子項目的坐標體系中

重載此方法的ViewGroup應該支持以下幾點:

    * 若矩形已經是可見的,則沒有東西會改變

    * 為使矩形區域全部可見,視圖將可以被滾動顯示

參數

child        發出請求的子視圖

rectangle    子項目坐標系內的矩形,即此子項目希望在屏幕上的定位

immediate   設為true,則禁止動畫和平滑移動滾動條

      返回值

            進行了滾動操作的這個組(group),是否處理此操作。

(23)public void requestLayout ()

當有改變引起當前視圖重新布局時,調用此函數。它將規划一個視圖樹的layout路徑。

 

(24)public void scrollTo (int x, int y)

設置當前視圖滾動到的位置。此函數會引起對onScrollChanged(int, int, int, int)函數的調用並且會讓視圖更新。

當前版本取消了在子視圖中的滾動。

參數

     x     滾動到的X位置

              y     滾動到的Y位置

 

(25)public void setFillViewport (boolean fillViewport)

設置當前滾動視圖是否將內容高度拉伸以填充視圖可視范圍(譯者注:viewport可視范圍,參見決定Scrollviewer里面Control的可視范圍)。

參數

     fillViewport    設置為true表示拉伸內容高度來適應視口邊界;其他設為false。

 

(26)public void setOverScrollMode (int mode)

為視圖設置over-scroll模式。有效的over-scroll模式有OVER_SCROLL_ALWAYS(缺省值),OVER_SCROLL_IF_CONTENT_SCROLLS(只允許當視圖內容大過容器時,進行over-scrolling)和OVER_SCROLL_NEVER。只有當視圖可以滾動時,此項設置才起作用。

(譯者注:這個函數是2.3 r1 中新增的,API Level 9。關於over-scroll這里譯為彈性滾動,即,參見帖子:類似iPhone的彈性ListView滾動

         參數

                   mode       The new over-scroll mode for this view.

 

(27)public void setSmoothScrollingEnabled (boolean smoothScrollingEnabled)

用來設置箭頭滾動是否可以引發視圖滾動。

參數

              smoothScrollingEnabled    設置箭頭滾動是否可以引起內容的滾動的bool值

 

(28)public final void smoothScrollBy (int dx, int dy)

類似於scrollBy(int, int),但是滾動時候是平緩的而不是立即滾動到某處。

參數

     dx   在X方向滾動的像素數

     dy   在Y方向滾動的像素數

 

(29)public final void smoothScrollTo (int x, int y)

類似於scrollTo(int, int),但是滾動時候是平緩的而不是立即滾動到某處。

參數

     x     要滾動到位置的X坐標

              y     要滾動到位置的Y坐標

 

受保護方法

(30)protected int computeScrollDeltaToGetChildRectOnScreen (Rect rect)

計算X方向滾動的總合,以便在屏幕上顯示子視圖的完整矩形(或者,若矩形寬度超過屏幕寬度,至少要填滿第一個屏幕大小)。

參數

     rect        矩形

返回值

滾動差值

 

(31)protected int computeVerticalScrollOffset ()

計算垂直方向滾動條的滑塊的偏移。此值用來計算滾動條軌跡的滑塊的位置。

范圍可以以任意單位表示,但是必須與computeVerticalScrollRange()computeVerticalScrollExtent()的單位一致。

缺省的偏移是在當前視圖滾動的偏移。

返回值

滾動條的滑塊垂直方向的偏移。

 

(32)protected int computeVerticalScrollRange ()

滾動視圖的可滾動范圍是所有子元素的高度。

返回值

由垂直方向滾動條代表的所有垂直范圍,缺省的范圍是當前視圖的畫圖高度。

 

(33)protected float getBottomFadingEdgeStrength ()

返回滾動底部的能見度。能見度的值的范圍是0.0(沒有消失)到1.0(完全消失)之間。缺省的執行返回值為0.0或者1.0,而不是他們中間的某個值。滾動時子類需要重載這個方法來提供一個平緩的漸隱的實現。

返回值

滾動底部能見度,值的范圍在浮點數0.0f到1.0f之間。

 

(34)protected float getTopFadingEdgeStrength ()

返回滾動頂部的能見度。能見度的值的范圍是0.0(沒有消失)到1.0(完全消失)之間。缺省的執行返回值為0.0或者1.0,而不是他們中間的某個值。滾動時子類需要重載這個方法來提供一個平緩的漸隱的實現。

返回值

滾動頂部能見度,值的范圍在浮點數0.0f到1.0f之間。

 

(35)protected void measureChild (View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec)

要求當前視圖的一個子視圖測量自己,同時兼顧到當前視圖的MeasureSpec的要求和它的空白。子視圖必須有MarginLayoutParams。比較復雜的工作是在getChildMeasureSpec中完成的。

參數

child              需要自己測量的子視圖

parentWidthMeasureSpec        當前視圖要求的寬度

parentHeightMeasureSpec              當前視圖要求的寬度

 

(36)protected void measureChildWithMargins (View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed)

要求當前視圖的一個子視圖測量自己,同時兼顧到當前視圖的MeasureSpec的要求和它的空白和邊界。子視圖必須有MarginLayoutParams。比較復雜的工作是在getChildMeasureSpec中完成的。

參數

child             需要測量的子視圖

parentWidthMeasureSpec       當前視圖要求的寬度

widthUsed    水平方向上由父視圖使用的空白 (也可能是視圖的其他子視圖使用的)

parentHeightMeasureSpec      當前視圖要求的寬度

heightUsed  垂直方向上由父視圖使用的空白 (也可能是視圖的其他子視圖使用的)

 

(37)protected void onLayout (boolean changed, int l, int t, int r, int b)

當前視圖需要為子視圖分配大小和位置時候調用,子類繼承必須要重載此方法並調用自己子視圖的layout函數。

參數

changed       當前視圖的新的大小或者位置

l     相對父視圖,左邊界位置

t     相對父視圖,上邊界位置

r     相對父視圖,右邊界位置

b    相對父視圖,下邊界位置

 

(38)protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)

測量視圖以確定其內容寬度和高度。此方法被measure(int, int)調用。需要被子類重寫以提供對其內容准確高效的測量。

約定:當重寫此方法時,你必須調用setMeasuredDimension(int, int)來保存當前視圖view的寬度和高度。不成功調用此方法將會導致一個IllegalStateException異常,是由measure(int, int)拋出。所以調用父類的onMeasure(int, int)方法是必須的。

父類的實現是以背景大小為默認大小,除非MeasureSpec(測量細則)允許更大的背景。子類可以重寫onMeasure(int,int)以對其內容提供更佳的尺寸。

如果此方法被重寫,那么子類的責任是確認測量高度和測量寬度要大於視圖view的最小寬度和最小高度(getSuggestedMinimumHeight() 和 getSuggestedMinimumWidth()),使用這兩個方法可以取得最小寬度和最小高度。

參數

widthMeasureSpec 受主窗口支配的水平空間要求。這個需求通過 View.MeasureSpec.進行編碼。

          heightMeasureSpec         受主窗口支配的垂直空間要求。這個需求通過 View.MeasureSpec.進行編碼。

 

         (39)protected void onOverScrolled (int scrollX, int scrollY, boolean clampedX, boolean clampedY)

       被overScrollBy(int, int, int, int, int, int, int, int, boolean)調用,來對一個over-scroll操作的結果進行響應。(譯者注:這個函數是2.3 r1 中新增的,API Level 9)

參數

scrollX     新的X滾動像素值

scrollY     新的Y滾動像素值

clampedX        當scrollX被over-scroll的邊界限制時,值為true

clampedY        當scrollY被over-scroll的邊界限制時,值為true

 

(40)protected boolean onRequestFocusInDescendants (int direction, Rect previouslyFocusedRect)

當在滾動視圖的子視圖中查找焦點視圖時,需要注意不要將焦點設置在滾動出屏幕外的控件上。此方法會比執行缺省的ViewGroup代價高,否則此行為也會設置為缺省

參數

             direction 指定下列常量之一:FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT

previouslyFocusedRect  能夠給出一個較好的提示的矩形(當前視圖的坐標系統)表示焦點從哪里得來。如果沒有提示為null。

返回值

是否取得了焦點

 

(41)protected void onSizeChanged (int w, int h, int oldw, int oldh)

布局期間當視圖的大小發生改變時調用。如果只是添加到視圖,調用時顯示的是舊值0。(譯者注:也就是添加到視圖時,oldw和oldh返回的是0)。

參數

w     視圖當前寬度

h     視圖當前高度

oldw       視圖改變前的寬度

oldh              視圖改變前的高度

 

25.3 ScrollView的幾個屬性

(1)android:scrollbarFadeDuration

設置滾動條淡出效果(從有到慢慢的變淡直至消失)時間,以毫秒為單位。Android2.2中滾動條滾動完之后會消失,再滾動又會出來,在1.5、1.6版本里面會一直顯示着。

(2)android:scrollbarSize

設置滾動條的寬度。

(3)android:scrollbarStyle

(4)設置滾動條的風格和位置。設置值:insideOverlay、insideInset、outsideOverlay、outsideInset。這里沒有試出太多效果。 

(5)android:scrollbarThumbHorizontal

設置水平滾動條的drawable。     

(6)android:scrollbarThumbVertical

 

設置垂直滾動條的drawable.

(7)android:scrollbarTrackHorizontal

設置水平滾動條背景(軌跡)的色drawable

(8)android:scrollbarTrackVertical

設置垂直滾動條背景(軌跡)的色drawable

(9)android:background

設置背景色/背景圖片。可以通過以下兩種方法設置背景為透明:"@android:color/transparent"和"@null"。注意TextView默認是透明的,不用寫此屬性,但是Buttom/ImageButton/ImageView想透明的話就得寫這個屬性了

 

25.4 ScrollView的使用

ScrollView卷軸視圖是指當擁有很多內容,一屏顯示不完時,需要通過滾動跳來顯示的視圖.的使用,因此我們這里利用動態的增加Button,當一屏顯示不完時,就可以看到滾動的效果了。

首先我們在xml布局中作如下聲明,

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"

 android:id="@+id/ScrollView" android:layout_width="fill_parent"

 android:layout_height="wrap_content" android:scrollbars="vertical">

 <LinearLayout android:id="@+id/LinearLayout"

  android:orientation="vertical" android:layout_width="fill_parent"

  android:layout_height="wrap_content">

  <TextView android:id="@+id/TestView" android:layout_width="fill_parent"

   android:layout_height="wrap_content" android:text="TestView0" />

  <Button android:id="@+id/Button" android:text="Button0" android:layout_width="fill_parent"

   android:layout_height="wrap_content"></Button>

 </LinearLayout>

</ScrollView>

 

然后在Activity中實現顯示並創建監聽:

// 創建一個線性布局

  mLayout = (LinearLayout) this.findViewById(R.id.LinearLayout);

  // 創建一個ScrollView對象

  sView = (ScrollView) this.findViewById(R.id.ScrollView);

  Button mBtn = (Button) this.findViewById(R.id.button_01);

  mBtn.setOnClickListener(mClickListener);// 添加點擊事件監聽

 }

 

 public boolean onKeyDown(int keyCode, KeyEvent event){

  Button b = (Button) this.getCurrentFocus();

  int count = mLayout.getChildCount();

  Button bm = (Button) mLayout.getChildAt(count-1);

 

  if(keyCode==KeyEvent.KEYCODE_DPAD_UP && b.getId()==R.id.button_01){

   bm.requestFocus();

   return true;

  }else if(keyCode==KeyEvent.KEYCODE_DPAD_DOWN && b.getId()==bm.getId()){

   this.findViewById(R.id.button_01).requestFocus();

   return true;

  }

  return false;

 }

 // Button事件監聽,當點擊第一個按鈕時增加一個button和一個textview

 private Button.OnClickListener mClickListener = new Button.OnClickListener() {

 

  private int index = 1;

 

  @Override

  public void onClick(View v) {

   TextView tView = new TextView(ScrollViewActivity.this);//定義一個TextView

   tView.setText("TextView" + index);//設置TextView的文本信息

   //設置線性布局的屬性

   LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(

     LinearLayout.LayoutParams.FILL_PARENT,

     LinearLayout.LayoutParams.WRAP_CONTENT);

   mLayout.addView(tView, params);//添加一個TextView控件

   Button button = new Button(ScrollViewActivity.this);//定義一個Button

   button.setText("Button" + index);//設置Button的文本信息

   button.setId(index++);

   mLayout.addView(button, params);//添加一個Button控件

   mHandler.post(mScrollToButton);//傳遞一個消息進行滾動

  }

 

 };

 private Runnable mScrollToButton = new Runnable() {

 

  @Override

  public void run() {

   int off = mLayout.getMeasuredHeight() - sView.getHeight();

   if (off > 0) {

    sView.scrollTo(0, off);//改變滾動條的位置

   }

  }

 

 };

 

顯示的效果如下:

 

25.5 補充資料

文章精選

Android ApiDemos/ScrollView2 添加自動滾動和智能焦點切換

[Android學習指南]使用ScrollView實現滾動效果

Android中ScrollView與ListView共用問題的解決方案

 

26 ProgressBar進度條

26.1 ProgressBar類概述

progressBar進度條是一個顯示進度的控件,Android提供了兩大類進度條樣式,長形進度條樣式progress-BarStyleHorizontal和圓形進度條progressBarStyleLarge.ProgressBar類的層次關系如下:

java.lang.Object

  android.view.View

   android.widget.ProgressBar

 

26.2 ProgressBar常用的方法

方法

功能描述

返回值

ProgressBar

3個構造函數:

ProgressBar(Context contex)

ProgressBar(Context contex,AttributeSet attrs)

ProgressBar(Context contex,AttributeSet attrs,intdefStyle)

 

null

onAttachedToWindow()

視圖附加到窗體時調用

void

onDraw(Canvas canvas)

繪制視圖時,該方法被調用

void

onMeasure(int widthMeasureSpec,int heightMeasureSpec)

該方法被重寫時,必須調用setMeasedDimension(int,int)來存儲已測量視圖的高度和寬度,否則將通過measure(int,int)拋出一個IllegalStateException異常

void

onDetachedFromWindow()

從窗體分離事件的響應方法。當視圖Progress從窗體上分離或移除時調用

void

addFocusables(ArrayList<View>views,int direction)

繼承自android.view.View的方法,用於為當前ViewGroup中的所有子視圖添加焦點獲取能力

void

addTouchables(ArrayList<View views>)

繼承自android.view.View的方法,用於為子視圖添加觸摸能力

void

getBaseline

繼承自android.view.View的方法。返回窗口空間的文本基准線到其頂邊界的偏移量

int

dispatchDisplayHint(int hint)

繼承自android.view.View的方法。分發視圖是否顯示的提示

void

dispatchDraw(Canvas canvas)

繼承自android.view.View的方法。調用次方法來繪制子視圖

void

 

 

26.3 ProgressBar的使用

要實現一個簡單的進度條的效果,我們可以首先在XML文件中聲明一個長形進度條和一個圓形進度條:

<TextView 

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:text="@string/hello"

    />

  <ProgressBar

    android:id="@+id/ProgressBar01"

    style="?android:attr/progressBarStyleHorizontal" //設置樣式為長形進度條

    android:layout_width="200dp"

    android:layout_height="wrap_content"

    android:visibility="gone"  //設置當前不可見

  />

  <ProgressBar

        android:id="@+id/ProgressBar02"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        style="?android:attr/progressBarStyleLarge" //設置樣式為圓形進度條

        android:max="100"

        android:progress="50"

        android:secondaryProgress="70"

       android:visibility="gone"  //設置當前不可見

  />

  <Button

    android:id="@+id/Button01"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

android:text="開始" />

 

然后在Activity中實現監聽並通過線程來改變ProgressBar的值:

/設置窗口模式,,因為需要顯示進度條在標題欄

       requestWindowFeature(Window.FEATURE_PROGRESS);

       setProgressBarVisibility(true);

       setContentView(R.layout.main);

      

       //取得ProgressBar

       m_ProgressBar = (ProgressBar) findViewById(R.id.ProgressBar01);

       m_ProgressBar2= (ProgressBar) findViewById(R.id.ProgressBar02);

       mButton01 = (Button)findViewById(R.id.Button01);

      

       m_ProgressBar.setIndeterminate(false);

       m_ProgressBar2.setIndeterminate(false);

      

       //當按鈕按下時開始執行,

        mButton01.setOnClickListener(new Button.OnClickListener()

        {

          @Override

          public void onClick(View v)

          {

            // TODO Auto-generated method stub

          

          //設置ProgressBar為可見狀態

          m_ProgressBar.setVisibility(View.VISIBLE);

          m_ProgressBar2.setVisibility(View.VISIBLE);

          //設置ProgressBar的最大值

          m_ProgressBar.setMax(100);

          //設置ProgressBar當前值

          m_ProgressBar.setProgress(0);

          m_ProgressBar2.setProgress(0);

 

          //通過線程來改變ProgressBar的值

              new Thread(new Runnable() {

                  public void run()

                  {

                     for (int i = 0; i < 10; i++)

                     {

                         try

                         {

                            intCounter = (i + 1) * 20;

                            Thread.sleep(1000);

 

                            if (i == 4)

                            {

                                Message m = new Message();

 

                                m.what = ProgressBarActivity.GUI_STOP_NOTIFIER;

                                ProgressBarActivity.this.myMessageHandler.sendMessage(m);

                                break;

                            }

                            else

                            {

                                Message m = new Message();

                                m.what = ProgressBarActivity.GUI_THREADING_NOTIFIER;

                                ProgressBarActivity.this.myMessageHandler.sendMessage(m);

                            }

                         }

                         catch (Exception e)

                         {

                            e.printStackTrace();

                         }

                     }

                  }

              }).start();

           }

       });

    }

 

      Handler myMessageHandler = new Handler()

      {

        // @Override

         public void handleMessage(Message msg)

         {

             switch (msg.what)

             {

             //ProgressBar已經是對大值

             case ProgressBarActivity.GUI_STOP_NOTIFIER:

                m_ProgressBar.setVisibility(View.GONE);

                m_ProgressBar2.setVisibility(View.GONE);

                Thread.currentThread().interrupt();

                break;

             case ProgressBarActivity.GUI_THREADING_NOTIFIER:

                if (!Thread.currentThread().isInterrupted())

                {

                    // 改變ProgressBar的當前值

                    m_ProgressBar.setProgress(intCounter);

                    m_ProgressBar2.setProgress(intCounter);

                   

                    // 設置標題欄中前景的一個進度條進度值

                    setProgress(intCounter*100);

                    // 設置標題欄中后面的一個進度條進度值

                    setSecondaryProgress(intCounter*100);//

                }

                break;

             }

             super.handleMessage(msg);

        }

      };

 

效果如下:

 

 

 

27 SeekBar拖動條

27.1 SeekBar類概述

SeekBar是ProgressBar的擴展,在其基礎上增加了一個可滑動的滑片(注:就是那個可拖動的圖標)。用戶可以觸摸滑片並向左或向右拖動,再或者可以使用方向鍵都可以設置當前的進度等級。不建議把可以獲取焦點的widget放在SeekBar的左邊或右邊。

SeekBar可以附加一個SeekBar.OnSeekBarChangeListener以獲得用戶操作的通知。

 

SeekBar類的層次關系如下:

public class SeekBar extends AbsSeekBar

 

java.lang.Object

         android.view.View

                android.widget.ProgressBar

                            android.widget.AbsSeekBar

                                     android.widget.SeekBar

 

27.2 SeekBar常用的方法

 

方法

功能描述

返回值

SeekBar

3個構造函數:

SeekBar(Context contex)

SeekBar(Context contex,AttributeSet attrs)

SeekBar(Context contex,AttributeSet attrs,intdefStyle)

null

setOnSeekBarChangeListener(SeekBar.OnSeekBarChangeListener)

用於注冊拖動條的監聽器,這個監聽器用於監聽改變拖動條狀態的事件

void

drawableStateChanged()

繼承自ProgressBar的方法。該方法在視圖狀態的變化影響到所顯示的可繪制對象的狀態時調用。

void

onAttacedToWindow()

繼承自ProgressBar的方法。該方法在視圖添加到窗體時調用

 

onDraw(Canvas canvas)

繼承自ProgressBar的方法。該方法在繪制視圖時調用

void

onMessure(int w,int h)

繼承自ProgressBar的方法。該方法被重寫時,必須調用setMeasedDimension(int,int)來存儲已測量視圖的高度和寬度,否則將通過measure(int,int)拋出一個IllegalStateException異常

void

 

27.3 SeekBar屬性

XML屬性

屬性名稱

描述

android:thumb

Seekbar上繪制的thumb(可拖動的那個圖標)

 

27.4 SeekBar的使用

在xml中聲明一個SeekBar,兩個TextView,一個用於顯示當前SeekBar的值,一個用於顯示調節的狀態(正在調節或者以及停止調節):

<SeekBar android:id="@+id/seek"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:max="100"

        android:progress="50"

        android:secondaryProgress="75" />

 

    <TextView android:id="@+id/progress"

         android:layout_width="fill_parent"

        android:layout_height="wrap_content" />

 

    <TextView android:id="@+id/tracking"

         android:layout_width="fill_parent"

        android:layout_height="wrap_content" />

 

然后在Activity中:

//取得SeekBar對象

       mSeekBar = (SeekBar) findViewById(R.id.seek);

       mSeekBar.setOnSeekBarChangeListener(this);

       mProgressText = (TextView) findViewById(R.id.progress);

       mTrackingText = (TextView) findViewById(R.id.tracking);

    }

 

    //在拖動中--即值在改變

    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch)

    {

       mProgressText.setText("當前值:"+progress);

    }

    public void onStartTrackingTouch(SeekBar seekBar)

    {

       mTrackingText.setText("正在調節");

    }

    //停止拖動

    public void onStopTrackingTouch(SeekBar seekBar)

    {

       mTrackingText.setText("停止調節");

    }

效果如下:

 

27.5 補充資料

補充

         文章鏈接

在android里做一個豎着的seekbar

http://blog.csdn.net/saintswordsman/archive/2010/01/23/5248233.aspx

Android UI設計 SeekBar拖動條用法

http://www.pocketdigi.com/20100813/36.html

 

28 RatingBar評分條

28.1 RatingBar類概述

RatingBar是基於SeekBar和ProgressBar的擴展,用星型來顯示等級評定。使用RatingBar的默認大小時,用戶可以觸摸/拖動或使用鍵來設置評分,它有兩種樣式(小風格用ratingBarStyleSmall,大風格用ratingBarStyleIndicator),其中大的只適合指示,不適合於用戶交互。

當使用可以支持用戶交互的RatingBar時,無論將控件(widgets)放在它的左邊還是右邊都是不合適的。

只有當布局的寬被設置為wrap  content時,設置的星星數量(通過函數setNumStars(int)或者在XML的布局文件中定義)將顯示出來(如果設置為另一種布局寬的話,后果無法預知)。

次級進度一般不應該被修改,因為他僅僅是被當作星型部分內部的填充背景。

 

RatingBar的層次關系如下所示:

public class RatingBar extends AbsSeekBar

 

java.lang.Object

         android.view.View

                android.widget.ProgressBar

                       android.widget.AbsSeekBar

                              android.widget.RatingBar

 

28.2 RatingBar的屬性

 XML屬性

屬性名稱

描述

android:isIndicator

RatingBar是否是一個指示器(用戶無法進行更改)

android:numStars

顯示的星型數量,必須是一個整形值,像“100”。

android:rating

默認的評分,必須是浮點類型,像“1.2”。

android:stepSize

評分的步長,必須是浮點類型,像“1.2”。

 

28.3 RatingBar的常用方法

公共方法       

        (1) public int getNumStars ()

返回顯示的星型數量

返回值: 顯示的星型數量

                           

 

(2)public RatingBar.OnRatingBarChangeListener getOnRatingBarChangeListener ()

返回值

監聽器(可能為空)監聽評分改變事件

 

(3)public float getRating ()

獲取當前的評分(填充的星型的數量)

返回值

當前的評分

 

(4)public float getStepSize ()

獲取評分條的步長

返回值

The step size.

步長

 

(5)public boolean isIndicator ()

返回值

                            判斷當前的評分條是否僅僅是一個指示器(注:即能否被修改)

 

(6)public void setIsIndicator (boolean isIndicator)

設置當前的評分條是否僅僅是一個指示器(這樣用戶就不能進行修改操作了)

參數

isIndicator       Bool值,是否是一個指示器

 

(7)public synchronized void setMax (int max)

設置評分等級的范圍,從0到max

參數

max         評分條最大范圍。

 

(8)public void setNumStars (int numStars)

設置顯示的星型的數量。為了能夠正常顯示它們,建議將當前widget的布局寬度設置為wrap content

參數

numStars         星型的數量

 

(9)public void setOnRatingBarChangeListener (RatingBar.OnRatingBarChangeListener listener)

設置當評分等級發生改變時回調的監聽器

參數

listener   監聽器

 

(10)public void setRating (float rating)

設置分數(星型的數量)

參數

rating      設置的分數

 

(11)public void setStepSize (float stepSize)

設置當前評分條的步長(step size)

參數

stepSize 評分條的步進。例如:如果想要半個星星,它的值為0.5。

 

受保護方法

(12)protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

權衡 view 和 content 來決定它的寬度和高度的整齊。它被measure(int, int) 調用 並且應該被子類所覆蓋,以便提供准確高效的布局測量。

規定: 當覆蓋這個方法的時候,你必須調用 setMeasuredDimension(int, int)以便存儲精確的視圖的寬和高。如果不這樣做的話將觸發llegalStateException異常,被函數 measure(int, int)拋出。調用父類 onMeasure(int, int)是合理的。

尺寸的基本類的實現默認是背景大小,除非通過MeasureSpec允許大的尺寸。子類應該覆蓋 onMeasure(int, int) 以便提供更好的布局大小。

如果這個方法被覆蓋,子類應該負責確保標准的寬和高至少是視圖的最小寬度和高度的值(分別為getSuggestedMinimumHeight()getSuggestedMinimumWidth()兩方法)。

參數

       widthMeasureSpec     受主窗口支配的水平空間要求。這個需求通過 View.MeasureSpec.進行編碼。

       heightMeasureSpec   受主窗口支配的垂直空間要求。這個需求通過 View.MeasureSpec.進行編碼。

 

 

28.4 RatingBar的使用

我們在xml中聲明三種 樣式的RatingBar:

<RatingBar android:layout_width="wrap_content"

 

       android:layout_height="wrap_content" style="?android:attr/ratingBarStyleIndicator"

 

       android:id="@+id/ratingbar_Indicator" />

 

    <RatingBar android:layout_width="wrap_content"

 

       android:layout_height="wrap_content" style="?android:attr/ratingBarStyleSmall"

 

       android:id="@+id/ratingbar_Small" android:numStars="20" />

 

    <RatingBar android:layout_width="wrap_content"

 

       android:layout_height="wrap_content" style="?android:attr/ratingBarStyle"

 

       android:id="@+id/ratingbar_default" />

 

在Activity中聲明並顯示:

final RatingBar ratingBar_Small = (RatingBar)findViewById(R.id.ratingbar_Small);

 

        final RatingBar ratingBar_Indicator = (RatingBar)findViewById(R.id.ratingbar_Indicator);

 

        final RatingBar ratingBar_default = (RatingBar)findViewById(R.id.ratingbar_default);

 

 

 

        ratingBar_default.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener(){

 

 

 

    public void onRatingChanged(RatingBar ratingBar, float rating,

 

      boolean fromUser) {

 

     ratingBar_Small.setRating(rating);

 

     ratingBar_Indicator.setRating(rating);

 

     Toast.makeText(RatingBarActivity.this, "rating:"+String.valueOf(rating),

 

       Toast.LENGTH_LONG).show();

 

    }});

 

28.5 補充資料

補充

         文章鏈接

                   Android 控件之RatingBar評分條

                   Android更換RatingBar圖片

                   [Android學習指南]RatingBar 評分條

 

 

29 ProgressDialog對話框中的進度條

29.1 ProgressDialog類概述

前面,我們學習了對話框和進度條,現在將進度條加入到對話框,使得對話框更加的完善。我們知道進度條有長形進度條和圓形進度條,所以也就有對話框中的長形進度條和對話框中的圓形進度條。

 

 

29.2 ProgressDialog中常用的方法

setProgressStyle : 設置進度條風格,風格為圓形,旋轉的或者風格為長形的;

setTitle : 設置ProgressDialog的標題

setMessage : 設置ProgressDialog的提示信息

setIcon :設置ProgressDialog的標題圖標

setIndeterminate :設置ProgressDialog的進度條是否不明確

setCancelable :設置ProgressDialog是否可以按回退鍵取消

setButton :設置ProgressDialog的一個Button(需要監聽Button事件)

show :顯示ProgressDialog

 

29.3 ProgressDialog的使用

要實現29.1節中圖形中所示的效果,我們首先在xml中聲明兩個Button:

<Button

    android:id="@+id/yuan_button01"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text="圓形進度條" />

  <Button

    android:id="@+id/chang_button02"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

android:text="長形進度條" />

 

在Activity中得到Button對象,並分別實現監聽,在監聽里面生成我們所需要的帶進度條的對話框,對於長形進度條我們需要用線程來實時更新進度條的值。具體代碼如下:

/得到按鈕對象

       mButton01 = (Button)findViewById(R.id.yuan_button01);

       mButton02 = (Button)findViewById(R.id.chang_button02);

      

       //設置mButton01的事件監聽

        mButton01.setOnClickListener(new Button.OnClickListener() {

           @Override

           public void onClick(View v)

           {

              // TODO Auto-generated method stub

             

              //創建ProgressDialog對象

              m_pDialog = new ProgressDialog(ProgressDialogActivity.this);

 

              // 設置進度條風格,風格為圓形,旋轉的

              m_pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

 

              // 設置ProgressDialog 標題

              m_pDialog.setTitle("提示");

             

              // 設置ProgressDialog 提示信息

              m_pDialog.setMessage("這是一個圓形進度條對話框");

 

              // 設置ProgressDialog 標題圖標

              m_pDialog.setIcon(R.drawable.imag1);

 

              // 設置ProgressDialog 的進度條是否不明確

              m_pDialog.setIndeterminate(false);

             

              // 設置ProgressDialog 是否可以按退回按鍵取消

              m_pDialog.setCancelable(true);

             

              // 設置ProgressDialog 的一個Button

              m_pDialog.setButton("確定", new DialogInterface.OnClickListener() {

                  public void onClick(DialogInterface dialog, int i)

                  {

                     //點擊“確定按鈕”取消對話框

                     dialog.cancel();

                  }

              });

 

              // 讓ProgressDialog顯示

              m_pDialog.show();

           }

       });

       

      //設置mButton02的事件監聽

        mButton02.setOnClickListener(new Button.OnClickListener() {

           @Override

           public void onClick(View v)

           {

              // TODO Auto-generated method stub

             

              m_count = 0;

             

              // 創建ProgressDialog對象

              m_pDialog = new ProgressDialog(ProgressDialogActivity.this);

             

              // 設置進度條風格,風格為長形

              m_pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

             

              // 設置ProgressDialog 標題

              m_pDialog.setTitle("提示");

             

              // 設置ProgressDialog 提示信息

              m_pDialog.setMessage("這是一個長形對話框進度條");

             

              // 設置ProgressDialog 標題圖標

              m_pDialog.setIcon(R.drawable.imag2);

             

              // 設置ProgressDialog 進度條進度

              m_pDialog.setProgress(100);

             

              // 設置ProgressDialog 的進度條是否不明確

              m_pDialog.setIndeterminate(false);

             

              // 設置ProgressDialog 是否可以按退回按鍵取消

              m_pDialog.setCancelable(true);

             

              // 讓ProgressDialog顯示

              m_pDialog.show();

             

              new Thread()

              {

                  public void run()

                  {

                     try

                     {

                         while (m_count <= 100)

                         {

                            // 由線程來控制進度。

                            m_pDialog.setProgress(m_count++);

                            Thread.sleep(100);

                         }

                         m_pDialog.cancel();

                     }

                     catch (InterruptedException e)

                     {

                         m_pDialog.cancel();

                     }

                  }

              }.start();

             

           }

       });

   

30 Notification、NotificationManager狀態欄提示

30.1 概述

當有未接電話或者短信的時候,在Android手機的頂部狀態欄會出現一個小圖標,提示用戶有沒有處理的快訊,這時用觸筆按住狀態欄往下拖動時就可以展開並查看這些快訊,Android提供了NotificationManager來管理這些狀態欄信息,提供了Notification來處理這些快訊信息。

 

30.2 Notification屬性

Notification常用的屬性:

 

audioStreamType :當聲音響起時,所用的音頻流的類型

 

contentIntent :當通知條目被點擊時,就執行被設置的Intent

 

contentView :當通知被顯示在狀態條上的時候,同時這個被設置的視圖被顯示

 

default 指定哪個值是要被設置為默認的

 

deleteIntent :當用戶點擊“Clear All Notifications”按鈕區域刪除所有通知的時候,這個被設置的Intent被執行

 

icon 狀態條所用的圖片

 

iconLevel :假如狀態條的圖片有幾個級別,就設置這里

 

ledARGB : LED燈的顏色

 

ledOffMS LED : 關閉時的閃光時間,以毫秒計算

ledOnMS LED :開始時的閃光時間,以毫秒計算

number :這個通知代表事件的號碼

sound :通知的聲音

tickerText :通知被顯示在狀態欄時,所顯示的信息

vibrate :振動模式

when :通知的時間戳

 

Notification常用的字段:

DEFAULT_ALL                  使用所有默認值,比如聲音,震動,閃屏等等

        DEFAULT_LIGHTS            使用默認閃光提示

        DEFAULT_SOUNDS         使用默認提示聲音

        DEFAULT_VIBRATE         使用默認手機震動 

      【說明】:加入手機震動,一定要在manifest.xml中加入權限:

                         <uses-permission android:name="android.permission.VIBRATE" />

        以上的效果常量可以疊加,即通過

                mNotifaction.defaults =DEFAULT_SOUND  |  DEFAULT_VIBRATE ;  

            或mNotifaction.defaults |=DEFAULT_SOUND   (最好在真機上測試,震動效果模擬器上沒有)

 

        //設置flag位

           FLAG_AUTO_CANCEL          該通知能被狀態欄的清除按鈕給清除掉

        FLAG_NO_CLEAR                  該通知能被狀態欄的清除按鈕給清除掉

        FLAG_ONGOING_EVENT      通知放置在正在運行

        FLAG_INSISTENT                    是否一直進行,比如音樂一直播放,知道用戶響應

 

 

30.3 Notification的方法

Notification.build構造Notification方法介紹:   

 void setLatestEventInfo(Context context , CharSequencecontentTitle,CharSequence  contentText,PendingIntent contentIntent)  

          

 功能: 顯示在拉伸狀態欄中的Notification屬性,點擊后將發送PendingIntent對象

參數: context             上下文環境

contentTitle      狀態欄中的大標題

contentText      狀態欄中的小標題

contentIntent    點擊后將發送PendingIntent對象

說明:要是在Notification中加入圖標,在狀態欄和狀態條中顯示圖標一定要用這個方法,否則報錯!

 

NotificationManager類的常用方法:

過獲取系統服務來獲取該對象:           

NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE) ;

public  void cancelAll()                                  移除所有通知 (只是針對當前Context下的Notification)

public  void cancel(int id)                                      移除標記為id的通知 (只是針對當前Context下的所有Notification)

public  void notify(String tag ,int id, Notification notification) 將通知加入狀態欄, 標簽為tag,標記為id

public  void notify(int id, Notification notification)           將通知加入狀態欄,,標記為id

 

30.4 Notification的使用

首先我們定義了2個XMl文件,一個xml中聲明了一個TextView和一個Button。一個xml中我們只有一個TextView.,這個TextView是用來查看快訊的。

main.xml:

<TextView

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"

       android:layout_weight="0"

       android:paddingBottom="4dip"

       />

<Button

       android:id="@+id/Button01"

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

        android:text="Button01"

       >

       <requestFocus/>

    </Button>

 

main2.xml:

<TextView 

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:text="謝謝使用!"

/>

 

在Activity NotificantionActivity01里面:

Button            m_Button1;

 

    //聲明通知(消息)管理器

    NotificationManager  m_NotificationManager;

    Intent            m_Intent;

    PendingIntent     m_PendingIntent;

    //聲明Notification對象

    Notification      m_Notification;

 

 

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState)

    {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.main);

       //初始化NotificationManager對象

       m_NotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

 

       //獲取4個按鈕對象

       m_Button1 = (Button) findViewById(R.id.Button01);

      

 

       //點擊通知時轉移內容

       m_Intent = new Intent(NotificantionActivity01.this, NotificantionActivity02.class);

       //主要是設置點擊通知時顯示內容的類

       m_PendingIntent = PendingIntent.getActivity(NotificantionActivity01.this, 0, m_Intent, 0);

       //構造Notification對象

       m_Notification = new Notification();

 

       m_Button1.setOnClickListener(new Button.OnClickListener() {

           public void onClick(View v)

           {

              //設置通知在狀態欄顯示的圖標

              m_Notification.icon = R.drawable.img1;

              //當我們點擊通知時顯示的內容

              m_Notification.tickerText = "Button1通知內容...........";

              //通知時發出默認的聲音

              m_Notification.defaults = Notification.DEFAULT_SOUND;

              //設置通知顯示的參數

              m_Notification.setLatestEventInfo(NotificantionActivity01.this, "Button1", "Button1通知", m_PendingIntent);

              //可以理解為執行這個通知

              m_NotificationManager.notify(0, m_Notification);

           }

       });

 

然后在NotificantionActivity02里:

//這里直接限制一個TextView

      setContentView(R.layout.main2);

 

顯示的效果為:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM