Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 手機控制項應用.

Similar presentations


Presentation on theme: "Chapter 4 手機控制項應用."— Presentation transcript:

1 Chapter 4 手機控制項應用

2 元件佈局 這個章節會介紹常用的元件佈局(Layout),會依序介紹LinearLayout、FrameLayout、RelativeLayout以及TableLayout四種元件佈局。

3 <LinearLayout>
線性佈局共有兩個方向: 垂直(vertical) 水平(horizontal) 決定垂直或是水平的屬性為Orientation android:orientation="vertical"

4 <LinearLayout>

5 <LinearLayout> - 範例
在這個範例中,使用了<TextView>元件,共使用了三個<TextView>,這三個元件都以垂直向下的方式來呈現

6 <LinearLayout> - 範例
布局文件(res/layout/main.xml): <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:text="這是第一列" android:textSize="22sp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> android:text="這是第二列" android:text="這是第三列" </LinearLayout> 此範例是使用setContentView來顯示main.xml,故只需要修改專案中的res/layout/main.xml即可

7 <LinearLayout> - 常用屬性設定
android:orientation 在<LinearLayout>中,此屬性代表元件的排列是垂直或水平佈局 android:layout_width 代表此元件佈局的寬度,若值為fill_parent則會填滿parent的寬度;若值為wrap_content則元件寬度會依照內容大小而調整

8 <LinearLayout> - 常用屬性設定
android:layout_height 代表此元件佈局的高度,若值為fill_parent則會填滿parent的高度;若值為wrap_content則元件高度會依照內容大小而調整 android:layout_margin 指定這個view距離上下左右的額外距離

9 <LinearLayout> - 常用屬性設定
android: layout_marginBottom 指定這個view距離下方的額外距離 android: layout_marginLeft 指定這個view距離左方的額外距離 android: layout_marginRight 指定這個view距離右方的額外距離 android: layout_marginTop 指定這個view距離上方的額外距離

10 <FrameLayout> FrameLayout是所有佈局中最單純的 若同個FrameLayout中若有數個元件
以最上層的元件為主 若同個FrameLayout中有同大小的元件 只會看到最上層的元件 若同個FrameLayout中有不同大小的元件 會看到由下至上的元件 FrameLayout是所有佈局中最單純的,在同一個FrameLayout中若有數個元件在內,則會以最上層的元件為主,若在同個FrameLayout當中有同大小的元件,則此時只會看到最上層的元件;若同一個FrameLayout當中有不同大小的元件,則會看到由下至上的元件。

11 <FrameLayout> - 範例
This is 蓋過 That is

12 <FrameLayout> - 範例
布局文件-1 (res/layout/main.xml) : <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <FrameLayout android:layout_height="fill_parent" android:layout_weight="1"> <!-- 最底層的元件 --> <EditText android:text="That is a framelayout example" android:layout_width="wrap_content" android:layout_height="wrap_content" />

13 <FrameLayout> - 範例
布局文件-2(res/layout/main.xml): <!-- 最上層的元件 --> <EditText android:text="This is" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </FrameLayout> </LinearLayout> 下層元件為"That is a framelayout example" 上層元件為"Thit is"

14 <RelativeLayout>
<RelativeLayout>會把此佈局內的元件利用各元件的id來做相對位置的佈局,如而常用屬性相對示意圖如圖所示,虛線框框代表新加入的元件。

15 <RelativeLayout> - 範例
用RelativeLayout展示如LinearLayout的結果

16 <RelativeLayout> - 範例
布局文件架構(res/layout/main.xml): <!-- 顯示第一行的TextView --> <!-- 顯示第二行的TextView --> TextView02" TextView01" <!-- 顯示第三行的TextView --> TextView03" TextView02" 在RelativeLayout中的第一個元件會被當成主要參考元件,在此範例中即為id為TextView01的<TextView>,接下來我們將id為TextView02的<TextView>排列在id為TextView01的<TextView>下方,設定Relative的方式如下: TextView01" 程式以TextView01為參考,TextView02置放在TextView01下方,TextView03放置在TextView02下方

17 <RelativeLayout> - 範例
布局文件架構(res/layout/main.xml): <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:text="這是第一列" android:textSize="30sp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> android:text="這是第二列" android:layout_height="wrap_content" /> android:text="這是第三列" /> </RelativeLayout> 此範例用到三個TextView,利用三個TextView作RelativeLayout

18 <RelativeLayout> - 常用屬性設定
android:layout_above 置於目標id元件的上方 android:layout_alignBaseline 置於與目標id元件同樣的基準線上 android:layout_alignBottom 讓自己的下邊界與目標id元件的下邊界在同一個位置

19 <RelativeLayout> - 常用屬性設定
android:layout_alignLeft 讓自己的左邊界與目標id元件的左邊界在同一位置 android:layout_alignParentBottom 若為true,讓自己的下邊界與Parent的下邊界同位置 android:layout_alignParentLeft 若為true,讓自己的左邊界與Parent的左邊界同位置

20 <RelativeLayout> - 常用屬性設定
android:layout_alignParentRight 若為true,讓自己的右邊界與Parent的右邊界同位置 android:layout_alignParentTop 若為true,讓自己的上邊界與Parent的上邊界同位置 android:layout_alignRight 讓自己的右邊界與目標id元件的右邊界在同一位置

21 <RelativeLayout> - 常用屬性設定
android:layout_alignTop 讓自己的上邊界與目標id元件的上邊界在同一個位置 android:layout_alignWithParentIfMissing 若設為true,當參考的目標id不可用時,會以Parent為參考目標 android:layout_below 置於目標id元件的下方

22 <RelativeLayout> - 常用屬性設定
android:layout_centerHorizontal 若為true,置於Parent水平位置的中心 android:layout_centerInParent 若為true,置於Parent水平以及垂直位置的中心 android:layout_centerVertical 若為true,置於Parent垂直位置的中心 android:layout_toLeftOf/toRightOf 置於目標id元件的左方/右方

23 <TableLayout> TableLayout顧名思義是由列(row)和行(column)所組成,而TableLayout的每一個列是由<TableRow>所構成,至於每個列中的行可以由各種元件所構成

24 <TableLayout> - 範例
範例使用了三個<TableRow>,意即有三個row。

25 <TableLayout> - 範例
布局文件-1(res/layout/main.xml): <?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TableRow android:layout_marginTop="20px"> <TextView android:layout_column="0" android:text="第一列\n第一行" android:textSize="22sp" android:layout_marginLeft="60px"/> android:layout_column="1" android:text="第一列\n第二行" android:layout_marginLeft="60px"/>/> </TableRow> 在程式的一開始先定義<TableLayout>,接下來在<TableLayout>內定義三個<TableRow>,即三個列,接下來再給每個列使用<TextView>元件來定義兩個行,而定義此元件在第幾行可使用layout_column="行的索引值"。

26 <TableLayout> - 範例
布局文件-2(res/layout/main.xml): android:layout_column="0" android:text="第二列\n第一行" android:textSize="22sp" android:layout_marginLeft="60px"/> <TextView android:layout_column="1" android:text="第二列\n第二行" android:layout_marginLeft="60px"/>/> </TableRow> <TableRow android:layout_marginTop="20px"> android:text="第三列\n第一行" android:text="第三列\n第二行" </TableLayout>

27 文字元件

28 TextView TextView是個基本常用的元件 下列敘述XML與Method相對應之屬性功能 可使用XML來操作

29 TextView – 屬性功能介紹 android:autoLink <-> setAutoLinkMask(int)
可讓文字上的連結自動變成可點擊的連結 android:gravity <-> setGravity(int) 設定文字在View中x軸和y軸相關數值 android:height <-> setHeight(int) 設定TextView的高度 android:width <-> setWidth(int) 設定TextView的寬度

30 TextView – 屬性功能介紹 android:hint <-> setHint(int)
當Text是空的時候,就會顯示hint中的文字 android:lines <-> setLines(int) 設置TextView高度為幾個Line的高度,值必須為整數型別 android:maxLength <-> setFilters(InputFilter) 設定TextView文字的最大長度

31 TextView – 屬性功能介紹 android:password <-> setTransformationMethod(Transformation) 讓Text顯示成其他符號,常用於輸入或顯示密碼時 android:text <-> setText(CharSequence) 顯示的文字 android:textStyle <-> setTypeface(Typeface) 設定文字樣式

32 TextView – 屬性功能介紹 android:textColor <-> setTextColor(ColorStateList) 設定文字的顏色 android:textColorLink <-> setLinkTextColor(int) 設定連結的顏色 android:textSize <-> setTextSize(float) 設定文字大小

33 TextView – 範例 若點擊上述的網址,則會自動開啟瀏覽器跳至指定之網頁
以下範例使用<TextView>做一個網頁連結的書籤,在裡面有兩個TextView,內容分別為"Google – 網址、手機號碼等),則會自動判斷連結的部分並對應到適合的應用程式上,如範例,若點擊網址部分,則會自動開啟瀏覽器至點擊的網址;若為手機號碼,則會跳至撥號的軟體上。 若點擊上述的網址,則會自動開啟瀏覽器跳至指定之網頁

34 TextView – 範例一 純粹用XML語法產生連結(res/layout/main.xml): 設置autoLink為web
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_height="wrap_content" android:gravity="center" android:autoLink="web" android:text="Google - /> android:text="Yahoo - /> </LinearLayout> 設置autoLink為web 在TextView中,若沒有將autoLink設為web,則文字中的網址就沒有連結功能,若今天要自動設置電話號碼連結,只需將autoLink設為all或phone即可。 設置autoLink為web

35 TextView – 範例二 布局文件(res/layout/main.xml): 用程式碼產生連結 – 1(TextView.java):
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > </LinearLayout> 用程式碼產生連結 – 1(TextView.java): package ncu.bnlab; import android.app.Activity; import android.os.Bundle; import android.text.util.Linkify; import android.view.Gravity; import android.widget.LinearLayout; import android.widget.TextView;

36 TextView – 範例二 用程式碼產生連結 – 2(TextView.java):
public class TextViewExample extends Activity { /** Called when the activity is first created. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); LinearLayout layout = (LinearLayout)findViewById(R.id.my_layout); TextView tv1 = new TextView(this); tv1.setGravity(Gravity.CENTER); tv1.setAutoLinkMask(Linkify.WEB_URLS); tv1.setText("Google - layout.addView(tv1); TextView tv2 = new TextView(this); tv2.setGravity(Gravity.CENTER); tv2.setAutoLinkMask(Linkify.WEB_URLS); tv2.setText("Yahoo - layout.addView(tv2); } 首先,要使用程式碼新增元件的話,必須使用到findViewById,故在xml裡面必須先給LinearLayout一個id – my_layout,而在程式碼部分宣告了一個layout物件,而此物件使用了findViewById去找剛剛在xml檔案所設定的id。 接下來產生兩個TextView物件tv1以及tv2,使用set相關的Method設定完物件屬性後,接著使用layout.addView將tv1和tv2加入layout當中。

37 TextView – autoLink屬性 android:autoLink <-> setAutoLinkMask(int)
none autoLink預設值 all <-> Linkify.ALL 目前所有連結種類 <-> Linkify. _ADDRESSES 連結 phone <-> Linkify. PHONE_NUMBERS 電話號碼連結 web <-> Linkify.WEB_URLS 網址連結

38 AutoCompleteTextView
AutoCompleteTextView可達到簡易自動完成Text的功能 假設已有定義台灣的縣市英文名稱,當輸入Ta時,程式會自動將符合Ta的縣市名稱給列出來,如範例所展示。

39 AutoCompleteTextView – 範例
此範例當中,宣告了一個TAIWAN的字串陣列,而內容則是各縣市的英文,如Taipei、Taichung等名稱。當我們在AutoCompleteTextView當中輸入Ta時,會自動搜尋到在TAIWAN這個陣列中符合Ta開頭的字串。

40 AutoCompleteTextView – 範例
布局文件(res/layout/main.xml): <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <AutoCompleteTextView android:text="" android:layout_height="wrap_content" /> </LinearLayout>

41 AutoCompleteTextView – 範例
程式碼(TextView.java): package ncu.bnlab; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; public class AutoCompleteTextViewExample extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, TAIWAN); AutoCompleteTextView TaiwanCity = (AutoCompleteTextView)findViewById(R.id.city); TaiwanCity.setAdapter(adapter); } private static final String[] TAIWAN = new String[] { "Keelung", "Taipei", "Taoyuan", "Hsinchu", "Miaoli", "Taichung", "Changhua", "Nantou", "Yunlin", "Chiayi", "Tainan", "Kaohsiung", "Pingtung ", "Yilan", "Hualien", "Taitung" };

42 表單元件

43 Button Button的layout方面會有兩種屬性 wrap_content fill_parent
layout_width為wrap_content時,這個button會依據button上的text長度為基準 fill_parent layout_width為fill_parent時,則會以parent最寬的長度為主

44 Button – 範例 利用XML建立Button即可

45 ImageButton ImageButton可以將圖片當作button的背景 利用此屬性 layout:src="圖片位置"

46 ImageButton – 範例 布局文件(res/layout/main.xml):
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" /> <ImageButton /> <ImageButton /> </LinearLayout> 由程式碼可看出,範例指定<ImageButton>的android:src屬性分別指定在drawable這個資源檔中的三張圖片,heart、lightning以及star。

47 RadioButton RadioButton為個別的一個按鈕
若要做成有多選一這種功能時,則需將這些RadioButton放置一個<RadioGroup>中

48 RadioButton – 範例

49 RadioButton – 範例 布局文件-1(res/layout/main.xml):
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:text="您對此次教學感到?" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <RadioGroup android:layout_height="wrap_content" android:orientation="horizontal“>

50 RadioButton – 範例 布局文件-2(res/layout/main.xml):
<RadioButton android:text="滿意" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true"/> android:text="普通" android:layout_height="wrap_content" /> android:text="不滿意" </RadioGroup> </LinearLayout> 首先,將三個RadioButton原件放置在一個Radio Group當中,在這個Radio Group中設置android:orientation為horizontal,則三個RadioButton會以水平方式來擺放,可看到第一個RadioButton中有一個屬性android:checked,若此屬性設為true代表在這個Group當中此RadioButton是預設的選項。

51 ToggleButton ToggleButton是一種類似開關的Button 開關上的文字也可以自訂 預設為 Off,點擊後變為 On
android:textOn和android:textOff當中的文字即為開關On或Off時顯示的文字

52 ToggleButton – 範例 此範例中,使用到一個簡單的事件處理,當開關變動時在開關下方的TextView會跟著改變。

53 ToggleButton – 範例 布局文件-1(res/layout/main.xml):
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ToggleButton android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:text="Now is Off"

54 ToggleButton – 範例 布局文件-2(res/layout/main.xml): <ToggleButton
android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="30sp" android:textOn="開" android:textOff="關"/> <TextView android:text="Now is Off" android:layout_height="wrap_content" /> </LinearLayout>

55 ToggleButton – 範例 程式碼-1(ToggleButtonExample.java):
public class ToggleButtonExample extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final TextView textView01 = (TextView)findViewById(R.id.TextView01); final ToggleButton toggleButton01 = (ToggleButton) findViewById(R.id.ToggleButton01); toggleButton01.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (toggleButton01.isChecked()) { textView01.setText("Now is ON"); } else { textView01.setText("Now is OFF"); } }); 首先在main.xml中使用到兩個<ToggleButton>和兩個<TextView>,TextView用來顯示ToggleButton的狀態。在ToggleButtonExample.java當中使用到兩個事件處理,首先使用findViewById分別找到各元件,在toggleButton01以及toggleButton02設置onClick事件處理並利用isCheck()來判斷toggleButton的開關狀態,再依照狀態改變TextView01和TextView02的文字內容。

56 ToggleButton – 範例 程式碼-2(ToggleButtonExample.java):
final TextView textView02 = (TextView)findViewById(R.id.TextView02); final ToggleButton toggleButton02 = (ToggleButton) findViewById(R.id.ToggleButton02); toggleButton02.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (toggleButton02.isChecked()) { textView02.setText("Now is ON"); } else { textView02.setText("Now is OFF"); } }); 在toggleButton01以及toggleButton02設置onClick事件處理並利用isCheck()來判斷toggleButton的開關狀態,再依照狀態改變TextView01和TextView02的文字內容。

57 CheckBox CheckBox只有兩種型態 checked unchecked CheckBox可用在勾選多項選擇時

58 CheckBox – 範例

59 CheckBox – 範例 布局文件-1(res/layout/main.xml): <TextView
android:text="你喜歡的顏色? (可複選)" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <LinearLayout android:orientation=“horizontal” android:layout_width="fill_parent" android:layout_height="wrap_content"> <CheckBox android:text="紅色" android:layout_height="wrap_content" /> android:text="黃色" android:text="綠色" </LinearLayout>

60 CheckBox – 範例 布局文件-2(res/layout/main.xml): <TextView
android:text="平常的休閒活動? (可複選)" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <CheckBox android:text="打球" android:layout_height="wrap_content" /> android:text="游泳" android:text="上網" </LinearLayout>

61 DatePicker DatePicker可讓使用者選擇年、月、日
當使用者按下button後,TextView會顯示DatePicker所選的日期。

62 DatePicker 布局文件-1(res/layout/main.xml):
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <DatePicker android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="15sp"/> <Button android:text="確定" android:layout_marginTop="25sp"/> <TextView android:text="" android:layout_marginTop="35sp"/> </LinearLayout>

63 DatePicker 程式碼(DatePickerExample.java):
public class DatePickerExample extends Activity { /** Called when the activity is first created. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final DatePicker datePicker = (DatePicker) findViewById(R.id.DatePicker01); final Button myButton = (Button) findViewById(R.id.Button01); final TextView textView = (TextView) findViewById(R.id.TextView01); myButton.setOnClickListener(new OnClickListener(){ public void onClick(View v) { int year = datePicker.getYear(); int month = datePicker.getMonth() + 1; int day = datePicker.getDayOfMonth(); textView.setText( year + "-" + month + "-" + day ); } }); 首先,對button設置一個OnClickListener,當button發生onClick事件時會到datePicker元件中抓年、月、日並將值讓textView來顯示。在datePicker中的month是由0~11,故在此才會在getMonth()後+1。

64 TimePicker TimePicker可讓使用者選擇時間 預設可讓使用者選擇AM或是PM
TimePicker可讓使用者選擇時間,在預設的功能下還可以選擇為AM或是PM,範例利用一個TextView來顯示被選擇的時間,若時間為5點17分,當選擇為AM時會顯示為5:17;當選擇成PM時則會變成17:17。

65 TimePicker – 範例 布局文件(res/layout/main.xml):
<TimePicker android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="15sp"/> <Button android:text="確定" android:layout_marginTop="25sp"/> <TextView android:text="" android:layout_marginTop="35sp" android:textSize="20sp"/>

66 TimePicker – 範例 程式碼(TimePickerExample.java):
public class TimePickerExample extends Activity public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final TimePicker timePicker = (TimePicker) findViewById(R.id.TimePicker01); final Button myButton = (Button) findViewById(R.id.Button01); final TextView textView = (TextView) findViewById(R.id.TextView01); myButton.setOnClickListener(new OnClickListener(){ public void onClick(View v) { int hour = timePicker.getCurrentHour(); int minute = timePicker.getCurrentMinute(); textView.setText( hour + " : " + minute ); } }); 在timePicker.getCurrentHour()所得到的小時為0~23,在此範例中也是對button設置OnClickListener,當有click事件發生時,會將TimerPicker的時間顯示在TextView上。

67 EditText EditText可讓使用者輸入文字
layout_width為wrap_content時,EditText的寬度會隨著輸入的字而變寬 當為fill_parent時則會固定為parent的寬度

68 EditText – 範例

69 ProgressBar ProgressBar可用於顯示程式執行進度 ProgressBar 有上述四種型態

70 ProgressBar – 範例 布局文件(res/layout/main.xml): 改變style即可變更ProgressBar的樣式
<ProgressBar android:layout_height=“wrap_content” android:layout_width=“200px” android:layout_gravity=“center_horizontal” android:layout_marginTop=“20sp” style=“?android:attr/progressBarStyleHorizontal” /> android:layout_width=“wrap_content” style=“?android:attr/progressBarStyleSmall” /> style=“?android:attr/progressBarStyle” /> style="?android:attr/progressBarStyleLarge" /> 改變style即可變更ProgressBar的樣式 在範例中,顯示了四種ProgressBar,而預設的PregressBar為第三個圓形的PregressBar,要更改不同種ProgressBar可在XML當中來修改: 1. style="?android:attr/progressBarStyleHorizontal" 2. style="?android:attr/progressBarStyleSmall" 3. style="?android:attr/progressBarStyle" 4. style="?android:attr/progressBarStyleLarge" 上述四種style分別對應範例的四種ProgressBar,而第三個style為預設的ProgressBar。

71 RatingBar RatingBar可用來製作評分系統 使用者可碰觸RatingBar的星星來達到評分 若碰觸星星的右半部則會加分
碰觸左半部則會扣分 最多為五顆星,星星間隔為0.5顆星

72 RatingBar – 範例

73 RatingBar – 範例 布局文件(res/layout/main.xml):
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <RatingBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:numStars="3" /> <TextView android:text="" android:textSize="50sp" android:layout_height="wrap_content" /> <RatingBar </LinearLayout>

74 RatingBar – 範例 程式碼(RatingBarExample.java):
public class RatingBarExample extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final TextView textView01 = (TextView) findViewById(R.id.TextView01); final TextView textView02 = (TextView) findViewById(R.id.TextView02); final RatingBar ratingBar01 = (RatingBar) findViewById(R.id.RatingBar01); ratingBar01.setOnRatingBarChangeListener(new OnRatingBarChangeListener(){ public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { textView01.setText(Float.toString(ratingBar01.getRating())); }}); final RatingBar ratingBar02 = (RatingBar) findViewById(R.id.RatingBar02); ratingBar02.setOnRatingBarChangeListener(new OnRatingBarChangeListener(){ public void onRatingChanged(RatingBar ratingBar, float rating,boolean fromUser) { textView02.setText(Float.toString(ratingBar02.getRating())); } 在這個範例中,使用了兩個<RatingBar>和兩個<TextView>元件,第一個RatingBar設為3星等,第二個設定為五星等,當RatingBar的評分改變時,在對應的TextView中顯示現在被評分的分數。在此對ratingBar01以及ratingBar02設置了OnRatingBarChangeListener,當rating改變時會觸發事件,而當事件被觸發後會將現在的評分顯示在相對應的textView01和textView02上。

75 對話視窗元件

76 AlertDialog AlertDialog為警告對話視窗,像是離開程式或是刪除檔案時會跳出的對話視窗元件

77 AlertDialog – 範例 程式碼-1(AlertDialogExample.java):
public class AlertDialogExample extends Activity public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final Button button01 = (Button) findViewById(R.id.Button01); final Button button02 = (Button) findViewById(R.id.Button02); button01.setOnClickListener(new OnClickListener(){ public void onClick(View arg0) { About(); } }); button02.setOnClickListener(new OnClickListener(){ Leave(); private void About() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("關於") .setMessage("這是 Alert Dialog") .show(); 在這個範例中,使用到兩個Button,各對兩個Button設置事件,一個為About(),一個為Leave()。而這兩個Method都會定義其AlertDialog的屬性,首先需要產生一個AlertDialog.Builder物件,接著在對builder設置屬性,如範例中的builder.set*****,較常用的builder屬性如表4.4.1。當設定好這些參數後,使用show()來顯示這個Dialog,在About()當中,在設定builder後直接加入".show()"讓Dialog顯示,也可如Leave()當中當設定完builder後,將builder create後,再用show()來顯示。

78 AlertDialog – 範例 程式碼-2(AlertDialogExample.java):
private void Leave() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("確定要離開本程式嗎?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub AlertDialogExample.this.finish(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { dialog.cancel(); }); AlertDialog about_dialog = builder.create(); about_dialog.show();

79 AlertDialog.Builder - 屬性
create() 創建一個AlertDialog setCancelable(boolean) 設為false時,使用者無法使用其他方式關閉這個對話視窗,只可使用對話視窗上給的操作方式來操作 setIcon(Drawable or int) 設置Title上的Icon setTitle(CharSequence or int) 設定要顯示的Title

80 AlertDialog.Builder - 屬性
setMessage(CharSequence or int) 設定要顯示的內容 setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener) 設定正向(左邊)的按鈕 setNegativeButton(CharSequence text, DialogInterface.OnClickListener listener) 設定反向(右邊)的按鈕 show() 顯示AlertDialog

81 ProgressDialog ProgressDialog可用於在等待其他程式或是在等待上傳時使用 ProgressDialog有兩種形式

82 ProgressDialog – 範例一 圓形的 ProgressDialog

83 ProgressDialog – 範例一 程式碼(AlertDialogExample01.java): 圓形的ProgressDialog
public class ProgressDialogExample extends Activity { int nowProgressStatus = 0; Handler myHandler = new public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final ProgressDialog dialog01 = ProgressDialog.show(this, "", "程式正在開啟中...", false); Thread thread01 = new Thread(new Runnable() { public void run() { while (nowProgressStatus < 100) { try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); nowProgressStatus+=5; } // While myHandler.post(new Runnable() { dialog01.cancel(); }); thread01.start(); 在這個範例當中,使用了預設的ProgressDialog,在程式一進行時,宣告了一個ProgressDialog並將其顯示出來,接著程式會等待執行緒中的nowProgressStatus加到100後,利用handler將這個ProgressDialog給cancel掉。例如當要執行一個程式或是做運算時,在運算一開始時可以使用ProgressDialog來表示程式或是運算正在進行,當程式結束或是運算結束後再將此ProgressDialog結束。 圓形的ProgressDialog

84 ProgressDialog – 範例二 長條型 ProgressDialog

85 ProgressDialog – 範例二 程式碼(AlertDialogExample02.java):
public class ProgressDialogExample02 extends Activity { int nowProgressStatus = 0; Handler myHandler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final ProgressDialog dialog02 = new ProgressDialog(this); dialog02.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog02.setMessage("讀取中..."); dialog02.show(); Thread thread02 = new Thread(new Runnable() { public void run() { while (nowProgressStatus < 100) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } nowProgressStatus+=5; myHandler.post(new Runnable() { dialog02.setProgress(nowProgressStatus); } }); } // While dialog02.cancel(); }}); thread02.start(); } 此範例與上述範例相似,主要差別在於ProgressDialog樣式不同,而樣式可從setProgressStyle來修改: dialog02.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 而可用的樣式有兩種,一種為STYLE_SPINNER,即圓形的ProgressDialog;另一種即是STYLE_HORIZONTAL,為長條狀的ProgressDialog ,而在STYLE_HORIZONTAL這種形式的ProgressDialog下,可透過setProgress()這個Method來顯示目前的進度以及完成的百分比。 在此範例中則是透過handler來幫忙serProgress()給予目前完成的進度。

86 DatePickerDialog DatePickerDialog除了選擇日期外,在預設的對話視窗上會顯示目前挑選的日期以及星期幾的資訊。

87 DatePickerDialog – 範例 程式碼(DatePickerDialogExample.java):
public class DatePickerDialogExample extends Activity { /** Called when the activity is first created. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); DatePickerDialog dpd = new DatePickerDialog(this,myOnDateSetListener,2009, 10, 05); dpd.show(); } private DatePickerDialog.OnDateSetListener myOnDateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // TODO Auto-generated method stub }; 在範例中,首先先產生一個DatePickerDialog物件,指定期日期為2009/11/05(月份為0-11,故在此10即代表11月),並指定一個事件myOnDateSetListener給此DatePickerDialog,而在此範例中當Set按鈕被按下時沒有做任何事情,若要加入功能時,可加在onDateSet(…)當中。

88 DatePickerDialog – 屬性 DatePickerDialog有兩種建構種類:
public DatePickerDialog (Context context, DatePickerDialog.OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) public DatePickerDialog (Context context, int theme, DatePickerDialog.OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) public DatePickerDialog (Context context, DatePickerDialog.OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) context 此Dialog所要執行的環境 callBack 當日期被set後的通知 year 初始的年份 monthOfYear 初始的月份,從0-11 dayOfMonth 初始的日 public DatePickerDialog (Context context, int theme, DatePickerDialog.OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) theme 此Dialog的theme

89 TimePickerDialog TimePickerDialog選擇時間外,預設在對話視窗會顯示所選的時間。

90 TimePickerDialog – 範例 程式碼(TimePickerDialogExample.java):
public class TimePickerDialogExample extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TimePickerDialog tpd = new TimePickerDialog(this, myTimeSetListener, 12, 25, false); tpd.show(); } private TimePickerDialog.OnTimeSetListener myTimeSetListener = new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(TimePicker view, int hourOfDay, int minute) { // TODO Auto-generated method stub }; 再範例中,首先先產生一個TimePickerDialog物件,初始時間為12點25分,並指定一個事件OnTimeSetListener給此TimePickerDialog,而在此範例中當Set按鈕被按下時沒有做任何事情,若要加入功能時,可加在onTimeSet (…)當中。

91 TimePickerDialog – 屬性 TimePickerDialog有兩種建構種類:
public TimePickerDialog (Context context, TimePickerDialog.OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView) public TimePickerDialog (Context context, int theme, TimePickerDialog.OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView) public TimePickerDialog (Context context, TimePickerDialog.OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView) context 此Dialog所要執行的環境 callBack 當時間被set後的通知 hourOfDay 初始的小時 minute 初始的分鐘 is24HourView 是24小時制或是AM/PM public TimePickerDialog (Context context, int theme, TimePickerDialog.OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView) theme 此Dialog的theme

92 選單元件

93 Options Menu Options Menu就是透過按手機或模擬器上的menu鍵顯示的功能表 最多可以顯示六項,稱為Icon Menu
超過六項就會以More的功能項來表示其餘的選項,稱為Expanded Menu。 當功能表第一次被打開時,系統會呼叫活動onCreateOptionsMenu()。覆寫該方法並產生傳遞給你的這個功能表對象。可以把這些功能表定義在XML中或是在JAVA中呼叫add()方法產生功能表。這個方法增加一個功能表項MenuItem,並傳回新建立的對象。你可以用傳回的MenuItem來設置其他屬性如圖示、快捷鍵以及這個功能表的其它設定。

94 Options Menu – 範例一 此種型式的Menu就稱為OptionsMenu

95 Options Menu – 範例一 程式碼-1(OptionsMenuEX.java):
public class OptionsMenu extends Activity { public static final int aboutBtnID = Menu.FIRST; public static final int exitBtnID = Menu.FIRST + 1; /** Called when the activity is first created. public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main); } public boolean onCreateOptionsMenu(Menu menu) menu.add(0, aboutBtnID, 0, "About"); menu.add(0, exitBtnID, 0, "Exit"); return true; 首先在範例一中,先將每個MenuItem的itemID設定好,並用整數儲存,接著覆寫onCreateOptionsMenu(), 其中add()的方法有好幾種,此處是採用有itemID參數的。這個方法這個add()方法有四個參數:groupID, itemID, order, 和title,GroupID在此範例中並沒有使用到,主要是用於關聯相同分組的Menu Item。itemID是用來識別MenuItem的唯一整數。order允許我們定義功能表的顯示順序。title當然是功能表的名稱。

96 Options Menu – 範例一 程式碼-2(OptionsMenuEX.java):
public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch( item.getItemId() ) { case aboutBtnID: openDialog(); break; case exitBtnID: finish(); } return true; public void openDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("About OptionsMenu"); builder.setTitle("About"); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { }).show();

97 Options Menu – 範例二 在範例二中我們加入超過六個項目至Menu中,可以發現最後一個MenuItem變成More Icon的樣式,點選後可以使用其他MenuItem

98 Options Menu – 範例二 程式碼-1(OptionsMenuEX.java):
public class OptionsMenu2 extends Activity { public static final int aboutBtnID = Menu.FIRST; public static final int exitBtnID = Menu.FIRST + 1; public static final int searchBtnID = Menu.FIRST + 2; public static final int addBtnID = Menu.FIRST + 3; public static final int playBtnID= Menu.FIRST + 4; public static final int delBtnID = Menu.FIRST + 5; public static final int openBtnID = Menu.FIRST + 6; /** Called when the activity is first created. public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main); } public boolean onCreateOptionsMenu(Menu menu) menu.add(0, aboutBtnID, 0, "About"); menu.add(0, exitBtnID, 0, "Exit"); menu.add(0, searchBtnID, 0, "Search"); menu.add(0, addBtnID, 0, "Add"); menu.add(0, playBtnID, 0, "Play"); menu.add(0, delBtnID, 0, "Delete"); menu.add(0, openBtnID, 0, "Open"); return true;

99 Options Menu – 範例二 程式碼-2(OptionsMenuEX2.java):
public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch( item.getItemId() ) case aboutBtnID: openDialog(); break; case exitBtnID: finish(); } return true; public void openDialog() AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("About OptionsMenu"); builder.setTitle("About"); builder.setPositiveButton(“OK”, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { }).show();

100 Options Menu – 範例三 在功能表中增加圖示

101 Options Menu – 範例三 程式碼(OptionsMenuEX.java): 透過setIcon()方法在功能表中增加圖示
public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, aboutBtnID, 0, "About").setIcon(R.drawable.icon); menu.add(0, exitBtnID, 0, "Exit").setIcon(R.drawable.icon); return true; } 透過setIcon()方法在功能表中增加圖示

102 Context Menu Android中的Context Menu與一般個人電腦中的滑鼠右鍵非常類似
當在View上,使用者長按螢幕不放兩秒,將會出現一個浮動功能表 Context Menu不支援圖示或快捷鍵 首先為了建立Context Menu,必須覆寫onCreateContextMenu() 和onContextItemSelected(),在onCreateContextMenu()中,可以使用add()方法來增加Menu Item,或者定義在XML中,並透過registerForContextMenu()為這個View註冊一個ContextMenu。

103 Context Menu – 範例

104 Context Menu – 範例 程式碼(ContextMenuEX.java):
public class ContextMenu extends Activity { public String checkedItem = ""; public static final int newBtnID = Menu.FIRST; public static final int openBtnID = Menu.FIRST + 1; public static final int closeBtnID = Menu.FIRST + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button fileBtn = (Button)findViewById(R.id.fileBtn); Button editBtn = (Button)findViewById(R.id.editBtn); registerForContextMenu(fileBtn); registerForContextMenu(editBtn); } public void onCreateContextMenu(android.view.ContextMenu conMenu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(conMenu, v, menuInfo); conMenu.setHeaderTitle("Context Menu"); conMenu.add(0, newBtnID, 0, "New").setNumericShortcut('1'); conMenu.add(0, openBtnID, 0, "Open").setCheckable(true); conMenu.add(0, closeBtnID, 0, "Close").setIcon(R.drawable.icon); public boolean onContextItemSelected(MenuItem item) { super.onContextItemSelected(item); return false;

105 Sub Menu 一個子功能表可以被加入任何功能表中,但不能加入另外的子功能表中。
當應用程式有很多功能可以被分類時,會非常好用,就像是一般電腦的功能表。

106 Sub Menu – 範例

107 Sub Menu – 範例 程式碼-1(SubMenuEX.java):
public class SubMenus extends Activity { public String checkedItem = ""; public static final int newBtnID = Menu.FIRST; public static final int openBtnID = Menu.FIRST + 1; public static final int closeBtnID = Menu.FIRST + public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main); Button fileBtn = (Button)findViewById(R.id.fileBtn); Button editBtn = (Button)findViewById(R.id.editBtn); registerForContextMenu(fileBtn); registerForContextMenu(editBtn); }

108 Sub Menu – 範例 程式碼-2(SubMenuEX.java):
public void onCreateContextMenu(android.view.ContextMenu conMenu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(conMenu, v, menuInfo); /* conMenu.setHeaderTitle("Context Menu"); conMenu.add(0, newBtnID, 0, "New").setNumericShortcut('1'); //利用數字選擇 conMenu.add(0, openBtnID, 0, "Open").setCheckable(true); //設定checkbox conMenu.add(0, closeBtnID, 0, "Close").setIcon(R.drawable.icon); //ContextMenu不支援icon*/ SubMenu sub = conMenu.addSubMenu("Submenu"); sub.add("Add..."); sub.add("Delete..."); } public boolean onContextItemSelected(MenuItem item) super.onContextItemSelected(item); return false; 子功能表透過addSubMenu()加入目前的已存在功能表中。該函式會傳回一個子功能表SubMenu對象,然後可以透過呼叫add()方法給增加功能表項目。

109 Spinner Spinner是一個widget,允許使用者從一群選項中選出其中一個。

110 Spinner – 範例

111 Spinner – 範例 布局文件-1(res/layout/main.xml): 首先我們將main.xml改寫成下列範例中的程式碼
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:orientation="vertical" android:padding="10dip" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:layout_height="wrap_content" android:layout_marginTop="10dip" android:text="Please select a planet:" /> <Spinner android:drawSelectorOnTop="true" </LinearLayout> 首先我們將main.xml改寫成下列範例中的程式碼

112 Spinner – 範例 布局文件(res/value/strings.xml): <string name="planet_prompt">Choose a item</string> 其中我們新增了Spinner的標籤,接著新增這段程式碼至strings.xml中。 布局文件(res/value/arrays.xml): <?xml version="1.0" encoding="UTF-8"?> <resources> <string-array name=“cards"> <item>VISA</item> <item>MasterCard</item> <item>JBC</item> <item>HSBC</item> <item>CitiBank</item> <item>SD</item> </string-array> </resources> 接著在res/value/中建立一下名為arrays.xml的文件,arrays.xml程式碼如下

113 Spinner – 範例 程式碼-1(SpinnerEX.java):
package ncu.bnlab.SpinnerExample; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.Spinner; public class SpinnerEX extends Activity { /** Called when the activity is first public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main); Spinner s = (Spinner)findViewById(R.id.spinner); 最後將Spinner的JAVA原始檔開啟,在onCreate()中加入程式碼。

114 Spinner – 範例 程式碼-2(SpinnerEX.java):
/* 設定功能表項目陣列,使用createFromResource方法 */ ArrayAdapter adapter = ArrayAdapter.createFromResource( this, R.array.cards, android.R.layout.simple_spinner_item); /* 設定選單 */ adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); /* 設定Adapter */ s.setAdapter(adapter); }

115 Notifying元件

116 Toast Notification 消息條通知是一個在視窗彈出的訊息,它只顯示內容所需的空間且使用者當前活動仍然保持可見和可互動。
這個通知自動淡入淡出,且不接受互動事件,因為消息條可以從一個後台服務Service中建立,即便應用程式不可見,它也將呈現出來。

117 Toast Notification 一個消息條是用來顯示簡短文字訊息的好方法,例如說「檔案已儲存」,當使用者正在注意螢幕時,這種方式就可以提醒使用者動作已完成。 一個消息條不能接受使用者互動事件;如果希望使用者回答並採取對應動作,可以考慮使用一個狀態條通知Status Bar Notification,在下一小節將會介紹。

118 Toast Notification 首先,Toast物件有一個maketext的方法,這個方法帶有三個參數:
應用程式內容 文字訊息 顯示時間長短 接著它會回傳一個初始化的Toast物件,在程式中可以使用show()方法來顯示。

119 Toast Notification 一般標準的Toast預設位置是靠底下偏中間,可以透過setGravity(int, int, int)方法改變,在下面的範例中程式設定讓Toast物件靠左上角顯示。 如果要讓Toast物件往右移動,增加第二個參數(x-postion)的數值。 如果要讓Toast物件往下移動,增加第三個參數(y-postion)的數值。

120 Toast Notification – 範例

121 Toast Notification – 範例
程式碼(ToastNotificationEX.java): public class ToastNotification extends Activity { /** Called when the activity is first created. public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main); /* 第一種makeText用法 */ Context context1 = getApplicationContext(); CharSequence text1 = "Short Toast"; int duration1 = Toast.LENGTH_SHORT; // 設定停留長短 Toast toast = Toast.makeText(context1, text1, duration1); toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0); //設定Toast物件位置 toast.show(); /* 第二種makeText用法 */ Context context2 = getApplicationContext(); CharSequence text2 = "Long Toast"; int duration2 = Toast.LENGTH_LONG; // 設定停留長短 Toast.makeText(context2, text2, duration2).show(); }

122 Status Bar Notification
一個狀態條通知會增加一個圖示到 系統狀態列上 一個可選的滾動訊息 在這個「通知」視窗中的一個擴展消息。 當使用者選擇這個擴展消息時,Android發出這個通知所定義的一個Intent(通常是啟動一個活動)。 也可配置這個通知使用聲音、震動和設備上的閃燈來警告用戶。

123 Status Bar Notification
當應用程式是以後台服務運行且需要通知使用者事件時,這類通知是一種理想的方式。 如果需要在活動仍處於焦點下時警告使用者一個發生的事件,可以使用對話框通知Dialog Notification。

124 Status Bar Notification
一個活動或服務可以起始一個狀態條通知,然而活動只有在啟動狀態及處於焦點狀態時才可以完成這個動作。 所以當使用者在使用其他應用程式或設備處於休眠狀態時,服務可以在背景中建立狀態條通知。

125 Status Bar Notification
一個活動或服務可以起始一個狀態條通知,然而活動只有在啟動狀態及處於焦點狀態時才可以完成這個動作。 所以當使用者在使用其他應用程式或設備處於休眠狀態時,服務可以在背景中建立狀態條通知。

126 Status Bar Notification – 範例

127 Status Bar Notification – 範例
程式碼(StatusBarNotificationEX.java): public class StatusBarNotification extends Activity { /** Called when the activity is first created. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); int icon = R.drawable.icon; // 通知圖示 CharSequence tickerText = "Hello!!!"; // ticker-text long when = System.currentTimeMillis(); // 通知時間 Context context = getApplicationContext(); // 應用程式內容 CharSequence contentTitle = "這是訊息標題"; // 訊息標題 CharSequence contentText = "這是訊息內文"; // 訊息內文 Intent notificationIntent = new Intent(this, StatusBarNotification.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); Notification notification = new Notification(icon, tickerText, when); notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); final int HELLO_ID = 1; mNotificationManager.notify(HELLO_ID, notification); // 傳送通知 } 使用Notification的類別去定義狀態條通知,像是狀態條圖示、額外訊息、聲音通知。 NotificationManager是Android的系統服務可以執行及管理所有通知,為了傳送通知給NotificationManager,必需使用getSystemService()方法先取得NotificationManager的參考,當要通知使用者時再呼叫notify()方法。

128 Dialog Notification 一個對話框通知一般是出現在當前活動前面的一個視窗。
背後的活動遺失焦點而由此對話框接受所有的使用者互動。 對話框通常用於和運行中應用程式直接相關的通知和短暫活動。 使用Notification的類別去定義狀態條通知,像是狀態條圖示、額外訊息、聲音通知。 NotificationManager是Android的系統服務可以執行及管理所有通知,為了傳送通知給NotificationManager,必需使用getSystemService()方法先取得NotificationManager的參考,當要通知使用者時再呼叫notify()方法。

129 Dialog Notification 應該使用對話框來顯示一個進度條或者一個需要使用者確認的訊息 例如說帶有「確認」和「取消」按鈕的警告。
也可將對話框作為構成應用程式界面整體的元件以及用於除了通知之外的其它目的。

130 顯示元件

131 ImageView 用於顯示一個圖樣,例如說一個圖示或圖片。

132 ImageView - 屬性功能介紹 android:adjustViewBounds <-> setAdjustViewBounds(boolean) 如果要讓ImageView根據drawable資源大小去調整邊界,必須將此值設為true android:cropToPadding 如果為真,此圖片將被裁剪成適合的大小 android:maxHeight <-> setMaxHeight(int) 設定最大高度

133 ImageView - 屬性功能介紹 android:maxWidth <-> setMaxWidth(int)
設定最大寬度 android:scaleType <-> setScaleType(ImageView.ScaleType) 控制圖片如何縮放或移動且配合ImageView的大小 android:src <-> setImageResource(int) 為此ImageView內容設定資源圖檔 android:tint <-> setColorFilter(int,PorterDuff.Mode) 設定著色的過濾器

134 ImageView – 範例

135 ImageView – 範例 程式碼-1(ImageViewEX.java):
public class ImageViewEX extends Activity { @Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); ImageView imageView = new ImageView(this); imageView.setImageResource(R.drawable.christmas); setContentView(imageView); } 將drawable中的圖檔資源置入imageView的圖片來源。

136 ListView Android 除了提供CheckBox與RadioButton的物件之外,還提供另一種更為方便且表現多樣化的物件 – ListView

137 ListView – 範例

138 ListView – 範例一程式碼 程式碼-1(ListViewEX.java):
public class ListViewEX extends Activity public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); String[] Data = {"網路概論","通訊網路實驗","通訊概論"}; ListView listView = new ListView(this); // 設定ListView選擇的方式 : // 單選:ListView.CHOICE_MODE_SINGLE // 多選:ListView.CHOICE_MODE_MULTIPLE listView.setChoiceMode( ListView.CHOICE_MODE_SINGLE ); ArrayAdapter vArrayData = new ArrayAdapter( this , android.R.layout.simple_list_item_single_choice , Data ); // 設定ListView的接收器,做為選項的來源 listView.setAdapter( vArrayData ); // ListView 設定為 ContentView setContentView(listView); } 此範例為ListView繼承Activity的用法,下一個範例則是繼承ListActivity的用法。 其中listView.setChoiceMode( ListView.CHOICE_MODE_SINGLE )可設定ListView選擇的方式,ListView.CHOICE_MODE_SINGLE為單選;ListView.CHOICE_MODE_MULTIPLE為多選。 並設定陣列接收器的樣式,android.R.layout.simple_list_item_single_choice為CheckBox;android.R.layout.simple_list_item_multiple_choice為RadioButton。

139 ListView – 範例二程式碼 程式碼-2(ListViewEX.java):
public class ListViewEX2 extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); String[] Data = { "葷食","素食","兩者皆可" }; ListView listView = this.getListView(); listView.setChoiceMode( ListView.CHOICE_MODE_SINGLE ); // ListView 的選項來源由陣列提供 this.setListAdapter( new ArrayAdapter( this , android.R.layout.simple_list_item_single_choice , Data )); } 範例二繼承ListActivity來呈現ListView,與前一個範例效果相同。

140 GridView GridView可以顯示一個二維滾動格框,也可搭配其他元件,呈現類似一般手機上的功能表。
範例二繼承ListActivity來呈現ListView,與前一個範例效果相同。

141 GridView – 範例 範例二繼承ListActivity來呈現ListView,與前一個範例效果相同。

142 GridView – 範例 GridView程式碼-1(GridViewEX.java):
public class GridViewEX extends Activity public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main); GridView gridview = (GridView) findViewById(R.id.gridview); gridview.setAdapter(new ImageAdapter(this)); } 這個範例主要是使用GridView搭配ImageAdapter當作資料來源,顯示圖片於GridView的格框之中。

143 GridView – 範例 ImageAdapter程式碼-1(ImageAdapter.java):
public class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context c) mContext = c; } public int getCount() return mThumbIds.length; public Object getItem(int position) return null; public long getItemId(int position) return 0; 通常ImageAdapter是繼承自BaseAdapter,GridView也是在手機上呈現九宮格效果的首選。

144 GridView – 範例 ImageAdapter程式碼-2(ImageAdapter.java):
public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(85, 85)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(8, 8, 8, 8); } else imageView = (ImageView) convertView; imageView.setImageResource(mThumbIds[position]); return imageView; private Integer[] mThumbIds = R.drawable.icon, R.drawable.christmas, R.drawable.favorite, R.drawable.ipod }; 另外需要注意的就是,匯入圖片至drawable中時,圖片檔名會有所限制,像是不能使用大寫以及其他一些特殊符號。

145 SurfaceView 依照傳統的作法,要快速更新畫面,如果做遊戲之類的應用
通常會新增執行緒處理工作後,使用handler傳送訊息給View顯示畫面 或在非使用者執行緒呼叫View。 做法就是透過SurfaceView的getHolder()取得SurfaceHolder,然後對SurfaceHolder的Canvas畫圖。

146 SurfaceView – 範例

147 SurfaceView – 範例 程式碼-1(SurfaceViewEX.java):
public class SurfaceViewEX extends Activity { public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(new MyView(this)); } //內部類別 class MyView extends SurfaceView implements SurfaceHolder.Callback SurfaceHolder holder; public MyView(Context context) super(context); holder = this.getHolder();//獲取Holder public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)

148 SurfaceView – 範例 程式碼-2(SurfaceViewEX.java):
@Override public void surfaceCreated(SurfaceHolder holder) { new Thread(new MyThread()).start(); } public void surfaceDestroyed(SurfaceHolder holder) //執行緒 class MyThread implements Runnable public void run() Canvas canvas = holder.lockCanvas(null);//獲得畫布 Paint mPaint = new Paint(); mPaint.setColor(Color.BLUE); canvas.drawRect(new RectF(40,60,80,80), mPaint); holder.unlockCanvasAndPost(canvas);//解鎖畫布並更新顯示 此範例是透過內部類別的執行緒去更新畫面,在後續的章節中會有更進階的用法介紹,如果是一般非遊戲畫面的更新,就不需用到SurfaceView。

149 WebView Webview是用於顯示web頁面的視景。 在活動中的任何一個瀏覽器或簡易地顯示一些線上內容。
它使用Webkit繪圖引擎去顯示頁面且包含 上一頁 下一頁 放大縮小 文字搜尋…等等方法

150 WebView – 範例

151 WebView – 範例 <uses-permission android:name="android.permission.INTERNET" /> 為了使活動可以在WebView存取Internet及讀取web頁面,需在AndroidManifest.xml中加入INTERNET權限 布局文件(res/layout/main.xml): <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:orientation="vertical">     <WebView                 android:layout_width="fill_parent"         android:layout_height="fill_parent"     /> </LinearLayout> 修改main.xml中的布局方式

152 WebView – 範例 程式碼(WebViewEX.java):
public class WebViewEX extends Activity { /** Called when the activity is first created. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); WebView webview; webview = (WebView) findViewById(R.id.webview); webview.getSettings().setJavaScriptEnabled(true); webview.loadUrl(" } 此處以Google網站作為連接範例

153 MapView 可在活動中顯示Google Map地圖畫面,並可於地圖上進行標示動作,與一般在瀏覽器上操作類似。
在此範例中需使用到Google Map API金鑰,此部分將於後面章節作詳細介紹。

154 MapView – 範例 在此範例中需使用到Google Map API金鑰,此部分將於後面章節作詳細介紹。

155 MapView – 範例 <uses-library android:name="com.google.android.maps" /> 首先必須在AndroidManifest.xml中的<application>標籤內加入Google Map API <uses-permission android:name="android.permission.INTERNET" /> 接著在AndroidManifest.xml中的<manifest>標籤內加入存取網路的權限

156 MapView – 範例 布局文件(res/layout/main.xml):
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <view class = "com.google.android.maps.MapView" android:clickable="true" android:apiKey=“你的apiKey" /> </LinearLayout> 其中android:apiKey需要去Google網站申請。

157 MapView – 範例 程式碼(MapViewEX.java):
public class MapViewEX extends MapActivity { /** Called when the activity is first created. protected boolean isRouteDisplayed() return false; } public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main); MapView mv = (MapView) findViewById(R.id.mapview); MapController controller = (MapController)mv.getController(); GeoPoint p = new GeoPoint((int) (25 * ),(int)(121.5 * )); controller.animateTo(p); controller.setZoom(15); 在本範例中繼承了MapActivity並在裡面使用MapView來顯示Google Map,並設定標記點,另外設定縮放大小。 但目前在2.0版中,模擬器無法顯示出地圖,在實機上可以,這部分需等Google提出解決方法。

158 客製化元件

159 客製化元件 介紹完Android所提供的各類元件後,其實Android本身也可以自行製作客製化元件來用,像是Button、TextView、 EditText、ListView、CheckBox、RadioButton 與一些其他有特殊用途的AutoCompleteTextView、ImageSwitcher和 TextSwitcher…等等搭配Layout組成新元件。

160 客製化元件 如果只是需要改變某個元件的小部分,那就可以直接覆寫元件中的方法即可。
完全客製化元件的方法可以建立一些用於顯示的圖形元件,也許一個像電壓的圖形計量器,或者是卡拉OK中的波紋隨著音樂滾動。

161 客製化元件 在Android中,可以用自訂的要求輕鬆地建立客製化元件,下面將簡單介紹如何創造客製化元件:
最為通用的毫無疑問是View類別,因此,最開始要建立一個基於此類別的一個子類別。 寫一個函數從XML文件中取得屬性和參數,當然也可以自行定義這些屬性和參數。 可能有必要撰寫本身的事件監聽器、修改函數和一些元件本身功能上的程式碼。 如果希望元件能夠顯示什麼東西,可能會重載 onMeasure() 函數。當兩個函數都用預設的,那onDraw() 函數將不會做任何事情,並且預設的 onMeasure() 函數會自動的設定一個100x100的尺寸,這個尺寸可能非我們所要的。 其他有必要重載的on...開頭 系列函數都需要重新撰寫一次。

162 客製化元件 onDraw()函數將會傳送一個 Canvas 對象,透過它即可在2D圖形上做任何事情,包含其他的一些標準和通用的元件、格式化本文,任何可以想到的東西都可以透過它呈現。 但此不包含3D圖形,如果想使用3D圖形,應該把父類別由View改為SurfaceView類,並使用獨立的執行緒。

163 客製化元件 onMeasure() 函數較為複雜一些,因為這個函數是呈現元件和容器互動的關鍵部分,onMeasure()應該重載,讓它能夠有效且準確的表現它所包含部分的測量值。 一旦測量寬度和高度出來後,就要立即呼叫setMeasuredDimension() 方法。

164 客製化元件 整體來說,執行onMeasure()函數分為以下幾個步驟:
重載的onMeasure()方法會被呼叫,高度和寬度參數同時也會牽涉到(widthMeasureSpec 和heighMeasureSpec兩個參數都是整數類型),同時還要考慮產品螢幕的尺寸限制。 元件要透過onMeasure()計算得到必要的測量長度和寬度,用來顯示元件。另外它可以實現一些規格以外的功能,像是滑動、捲動、裁切…等等。 一旦高度和寬度計算出來之後,必須呼叫setMeasuredDimension(int width, int height),否則就會導致系統異常。

165 課後習題 在<LinearLayout>中有兩種方向,請問要更改Layout方向的屬性為何?
請問<RelativeLayout>的佈局概念為何?試舉例說明。 試說明<TableLayout>和<TableRow>之間的關係。 如何讓<TextView>中的文字有自動連結的功能? 如何讓某個RadioButton為預設勾選項目? ProgressBar有幾種樣式?若要更改樣式要如何修改?

166 課後習題 Options Menu最多可顯示幾個項目,若超過上限會如何? ContextMenu是否可支援圖示或快捷鍵?
Toast可否更改顯示時間之間隔?需如何修改? StatusBarNotification如欲通知使用者需在程式中呼叫哪個方法? ListView如何設定單選或多選? 若要實現手機上之程式選單,可使用本章中何種元件? 如需在手機上使用MapView,需在AndroidManifest.xml加入哪項指令?


Download ppt "Chapter 4 手機控制項應用."

Similar presentations


Ads by Google