lab 5

31
Lab5: Làm việc với UI 1. Tạo UI từ XML và Java Code a. XML Tạo layout bằng main_layout.xml với nội dung: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <!-- NAME CONTAINER --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/nameText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@+string/name_text" /> <TextView android:id="@+id/nameValueText" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <!-- ADDRESS CONTAINER --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/addrText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@+string/addr_text" /> <TextView android:id="@+id/addrValueText" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout>

Upload: vinhnghi87

Post on 22-Oct-2014

79 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Lab 5

Lab5: Làm việc với UI

1. Tạo UI từ XML và Java Code

a. XML

Tạo layout bằng main_layout.xml với nội dung:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <!-- NAME CONTAINER --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/nameText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@+string/name_text" /> <TextView android:id="@+id/nameValueText" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout><!-- ADDRESS CONTAINER --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/addrText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@+string/addr_text" /> <TextView android:id="@+id/addrValueText" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout></LinearLayout>

b. Java code:

i. Thêm các biến trước hàm onCreate() của Activity

private LinearLayout nameContainer; private LinearLayout addressContainer; private LinearLayout parentContainer;

ii. Viết các hàm sau với nội dung

private void createNameContainer() { nameContainer = new LinearLayout(this); nameContainer.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

Page 2: Lab 5

nameContainer.setOrientation(LinearLayout.HORIZONTAL); TextView nameLbl = new TextView(this); nameLbl.setText("Name: "); nameContainer.addView(nameLbl);TextView nameValueLbl = new TextView(this); nameValueLbl.setText("John Doe"); nameContainer.addView(nameValueLbl); } private void createAddressContainer() { addressContainer = new LinearLayout(this); addressContainer.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); addressContainer.setOrientation(LinearLayout.VERTICAL); TextView addrLbl = new TextView(this); addrLbl.setText("Address:"); TextView addrValueLbl = new TextView(this); addrValueLbl.setText("911 Hollywood Blvd"); addressContainer.addView(addrLbl); addressContainer.addView(addrValueLbl); } private void createParentContainer() { parentContainer = new LinearLayout(this); parentContainer.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); parentContainer.setOrientation(LinearLayout.VERTICAL); parentContainer.addView(nameContainer); parentContainer.addView(addressContainer); }

iii. Thêm đoạn code trong onCreate() của Activity

createNameContainer(); createAddressContainer(); createParentContainer(); setContentView(parentContainer);

c. Chạy chương trình cho từng trường hợp và so sánh layout giữa XML và Java code.

2. Làm việc với TextView

a. Tạo New Project làm việc với TextView

b. Tạo new string resource với nội dung:

Page 3: Lab 5

<string name="link_text_auto"><b>text1:</b> This is some text. In this text are some things that are actionable. For instance, you can click on http://www.google.com and it will launch the web browser. You can click on google.com too. And, if you click on (415) 555-1212 it should dial the phone. </string> <string name="link_text_manual"><b>text2:</b> This is some other text, with a <a href="http://www.google.com">link</a> specified via an &lt;a&gt; tag. Use a \"tel:\" URL to <a href="tel:4155551212">dial a phone number</a>. </string>

c. Tạo link.xml layout với nội dung:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content">

<!-- Four TextView widgets, each one displaying text containing links. --> <!-- text1 automatically linkifies things like URLs and phone numbers. --> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/text1" android:layout_width="match_parent" android:layout_height="match_parent" android:autoLink="all" android:text="@string/link_text_auto" />

<!-- text2 uses a string resource containing explicit <a> tags to specify links. --> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/text2" android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/link_text_manual" />

<!-- text3 builds the text in the Java code using HTML. --> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/text3" android:layout_width="match_parent" android:layout_height="match_parent" />

Page 4: Lab 5

<!-- text4 builds the text in the Java code without using HTML. --> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/text4" android:layout_width="match_parent" android:layout_height="match_parent" />

</LinearLayout>d. Trong Java code, setContentView(R.layout.link), thêm đoạn code

TextView t2 = (TextView) findViewById(R.id.text2); t2.setMovementMethod(LinkMovementMethod.getInstance());

TextView t3 = (TextView) findViewById(R.id.text3);t3.setText(

Html.fromHtml("<b>text3:</b> Text with a " +"<a href=\"http://www.google.com\">link</a> " +"created in the Java source code using HTML."));

t3.setMovementMethod(LinkMovementMethod.getInstance());

SpannableString ss = new SpannableString("text4: Click here to dial the phone.");

ss.setSpan(new StyleSpan(Typeface.BOLD), 0, 6,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

ss.setSpan(new URLSpan("tel:4155551212"), 13, 17,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

TextView t4 = (TextView) findViewById(R.id.text4);t4.setText(ss);

t4.setMovementMethod(LinkMovementMethod.getInstance());

e. Chạy chương trình

3. Làm việc AutoCompleteTextView

a. Tạo new project HelloAutoComplete

b. Tạo xml file với tên list_item.xml được lưu trong /res/layout/ với nội dung:

<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:padding="10dp"    android:textSize="16sp"    android:textColor="#000"></TextView>

c. Tạo main_layout.xml file trong /res/layout với nội dung:

Page 5: Lab 5

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:orientation="horizontal"    android:layout_width="fill_parent"     android:layout_height="wrap_content"    android:padding="5dp">    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Country" />    <AutoCompleteTextView android:id="@+id/autocomplete_country"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_marginLeft="5dp"/></LinearLayout>

d. Trong onCreate() thêm đoạn code với nội dung:

    setContentView(R.layout.main_layout);

    AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES);    textView.setAdapter(adapter);

e. Tạo string array trong class Activity, trên hàm onCreate() với nội dung:

static final String[] COUNTRIES = new String[] {  "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",  "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",  "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",  "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",  "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",  "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory",  "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",  "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",  "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",  "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",  "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",  "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",  "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",  "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",  "Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia",  "French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar",

Page 6: Lab 5

  "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",  "Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary",  "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica",  "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",  "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",  "Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands",  "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",  "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",  "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand",  "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas",  "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru",  "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",  "Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena",  "Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon",  "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal",  "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",  "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea",  "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden",  "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas",  "The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",  "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",  "Ukraine", "United Arab Emirates", "United Kingdom",  "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan",  "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara",  "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"};

f. Chạy chương trình

4. Làm việc với Button control:

a. Sử dụng link http://developer.android.com/resources/tutorials/views/hello-formstuff.html

Page 7: Lab 5

5. Làm việc với ListView control:

a. Sử dụng link http://developer.android.com/resources/tutorials/views/hello-listview.html

6. Làm việc với GridView control:

a. Sử dụng link http://developer.android.com/resources/tutorials/views/hello-gridview.html

7. Làm việc với DatePicker control:

a. Sử dụng link http://developer.android.com/resources/tutorials/views/hello-datepicker.html

8. Làm việc với TimePicker control:

a. Sử dụng link http://developer.android.com/resources/tutorials/views/hello-timepicker.html

9. Làm việc với AnalogClock, DigitalClock control:

a. Tạo New Project, trong layout.xml thêm đoạn code với nội dung

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" >   <AnalogClock android:id="@+id/clock1" android:layout_width="wrap_content" android:layout_height="wrap_content" />  <DigitalClock android:id="@+id/clock2" android:layout_width="wrap_content" android:layout_height="wrap_content" />  </LinearLayout>

b. Run ứng dụng

10. Làm việc với MapView control:

a. Tạo new project sử dụng target platform Google APIs.

b. Khai báo thư viện Map trong Manifest file, thêm đoạn code trong <application> node

<uses-library android:name="com.google.android.maps" />

Page 8: Lab 5

c. Cần truy cập internet để truy cập Google Service, nên thêm quyền truy cập Internet, trong node <manifest>

<uses-permission android:name="android.permission.INTERNET" />d. Trong layout.xml file sử dụng com.google.android.maps.MapView như node

chính

<?xml version="1.0" encoding="utf-8"?><com.google.android.maps.MapView    xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/mapview"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:clickable="true"    android:apiKey="Your Maps API Key goes here"/>

e. Thay đổi apiKey thuộc tính

android:apiKey="0bwvbWfMyf-i3Ze41_w446AJ9dDCQK30lTh4uyw"

f. Mở Java code, change extends Activity là MapActivity class

g. Overide phương thức isRouteDisplayed() có thể yêu cầu Google Service cung cấp bất cứ thông tin tuyến.Trong trường hợp này, return false.

@Overrideprotected boolean isRouteDisplayed() {    return false;}

h. Thêm code từ onCreated()

    MapView mapView = (MapView) findViewById(R.id.mapview);    mapView.setBuiltInZoomControls(true);

i. Save ứng dụng

j. From Explorer ứng dụng, kích chuột phải vào tên project, chọn Android Tool -> Export signed Application Package

k. Lựa chọn project to export -> Next -> chọn Use existing keystore -> Location (chọn path chứa file nuance_internal.keystore (đã lưu

trong “/Lab/resource/” folder)), chọn Password -> Next

l. Key alias password -> use existing key -> chọn Password

m. Chọn đường dẫn đến APK file đích

n. Cài đặt APK file sử dụng ADB tool

Page 9: Lab 5

11. Làm việc với Gallery control:

a. Sử dụng link: http://developer.android.com/resources/tutorials/views/hello-gallery.html

12. Làm việc với WebView control:

a. Sử dụng Link: http://developer.android.com/resources/tutorials/views/hello-webview.html

13. Làm việc với LinearLayout control:

a. Sử dụng link: http://developer.android.com/resources/tutorials/views/hello-linearlayout.html

14. Làm việc với RelativeLayout control:

a. Sử dụng link: http://developer.android.com/resources/tutorials/views/hello-relativelayout.html

15. Làm việc với TableLayout control:

a. Sử dụng link: http://developer.android.com/resources/tutorials/views/hello-tablelayout.html

16. Làm việc với TabLayout control:

a. Sử dụng link: http://developer.android.com/resources/tutorials/views/hello-tabwidget.html

17. Làm việc với Menu từ Java code:

a. Tạo new project

b. Khởi tạo vài const trong Activity với nội dung sau

final static public int EDIT_CONTACT = 0;final static public int DELETE_CONTACT = 1;final static public int EXIT = 2;

c. Override onCreateOptionsMenu() trong Activity với nội dung sau

@Override public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub menu.add(0,EDIT_CONTACT,0,"Edit Contact").setIcon(android.R.drawable.star_on);

menu.add(0,DELETE_CONTACT,0,"Delete Contact").setIcon(android.R.drawable.star_off);

Page 10: Lab 5

menu.add(0,EXIT,0,"Exit").setIcon(android.R.drawable.star_off);

return super.onCreateOptionsMenu(menu); }

d. Override onCreateOptionsMenu() trong Activity với nội dung sau

@Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()){

case EDIT_CONTACT: { Toast.makeText(getApplicationContext(), "Item Edit

Contact", Toast.LENGTH_SHORT).show(); } case DELETE_CONTACT : { Toast.makeText(getApplicationContext(), "Delete

Contact", Toast.LENGTH_SHORT).show(); } case EXIT : { Toast.makeText(getApplicationContext(), "Exit",

Toast.LENGTH_SHORT).show(); }

}

return super.onOptionsItemSelected(item); }

e. Run ứng dụng

18. Làm việc với Toast Notification :

a. Tạo New Project

b. Thêm Button vào trong main.xml layout với nội dung

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

android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent"><Button android:layout_width="wrap_content"

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

android:text="Show Toast"></Button>

Page 11: Lab 5

</LinearLayout>

c. Tạo mới toast_layout.xml với nội dung

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toast_layout_root" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:background="#FFFFFF" > <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginRight="10dp" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="fill_parent" android:textColor="#000000" /></LinearLayout>

d. Trong onCreate() thêm đoạn code với nội dung

Button bt = (Button) findViewById(R.id.button1); bt.setOnClickListener(new OnClickListener() {

@Overridepublic void onClick(View v) {

// TODO Auto-generated method stubLayoutInflater inflater = getLayoutInflater();View layout =

inflater.inflate(R.layout.toast_layout, (ViewGroup)

findViewById(R.id.toast_layout_root));

ImageView image = (ImageView) layout.findViewById(R.id.image);

image.setImageResource(R.drawable.android);

TextView text = (TextView) layout.findViewById(R.id.text);

text.setText("Hello! I'm happy!");

Toast toast = new Toast(getApplicationContext());

toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);

toast.setDuration(Toast.LENGTH_LONG);toast.setView(layout);toast.show();

}

Page 12: Lab 5

});

e. Chạy ứng dụng

19. Làm việc với Status bar Notification :

a. Tạo new Project

b. Thêm Button vào trong main.xml layout với nội dung

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

android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent"><Button android:layout_width="wrap_content"

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

android:text="Show Toast"></Button>

</LinearLayout>

c. Trong onCreate() thêm vào đoạn code sau

Button bt = (Button) findViewById(R.id.button1); bt.setOnClickListener(new OnClickListener() {

@Overridepublic void onClick(View v) {

// TODO Auto-generated method stubShowNotification();

}});

d. Tạo ShowNotification() function với nội dung sau

private void ShowNotification() { String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); int icon = R.drawable.icon; CharSequence tickerText = "Hello"; long when = System.currentTimeMillis();

Notification notification = new Notification(icon, tickerText, when); Context context = getApplicationContext(); CharSequence contentTitle = "Notification"; CharSequence contentText = "Hello all friends"; Intent notificationIntent = new Intent(this, NotificationActivity.class);

Page 13: Lab 5

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); final int HELLO_ID = 1;

mNotificationManager.notify(HELLO_ID, notification); }

e. Tạo mới Activity với tên NotificationActivity

f. Thêm layout vào NotificationActivity với nội dung tùy thích

g. Run chương trình

20. Làm việc với AlertDialog:

a. Tạo new project

b. Định nghĩa const trong Activity

private static final int DIALOG_YES_NO_MESSAGE = 1; private static final int DIALOG_YES_NO_LONG_MESSAGE = 2; private static final int DIALOG_LIST = 3;

c. Trong layout.xml thêm 3 button

<Button android:id="@+id/two_buttons" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/alert_dialog_two_buttons"/> <Button android:id="@+id/two_buttons2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/alert_dialog_two_buttons2"/> <Button android:id="@+id/select_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/alert_dialog_select_button"/>

d. Override onCreateDialog(int) trong Activity và thêm đoạn code với nội dung sau

switch (id) { case DIALOG_YES_NO_MESSAGE: return new AlertDialog.Builder(this) .setTitle(R.string.alert_dialog_two_buttons_title) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) {

/* User clicked OK so do some stuff */

Page 14: Lab 5

} }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) {

/* User clicked Cancel so do some stuff */ } }) .create(); case DIALOG_YES_NO_LONG_MESSAGE: return new AlertDialog.Builder(this) .setTitle(R.string.alert_dialog_two_buttons_msg) .setMessage(R.string.alert_dialog_two_buttons2_msg) .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked OK so do some stuff */ } }) .setNeutralButton(R.string.alert_dialog_something, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) {

/* User clicked Something so do some stuff */ } }) .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) {

/* User clicked Cancel so do some stuff */ } }) .create(); case DIALOG_LIST: return new AlertDialog.Builder(this) .setTitle(R.string.select_dialog) .setItems(R.array.select_dialog_items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) {

// User clicked so do some stuff String[] items = getResources().getStringArray(R.array.select_dialog_items); Toast.makeText(getBaseContext(), "selected Item = " + items[which].toString(), Toast.LENGTH_LONG).show(); }

Page 15: Lab 5

}) .create(); }

e. Tạo arrays.xml với nội dung sau

<string-array name="select_dialog_items"> <item>Every Monday</item> <item>Every Tuesday</item> <item>Every Wednesday</item> <item>Every Thursday</item> <item>Every Friday</item> <item>Every Saturday</item> <item>Every Sunday</item> </string-array>

f. Thêm đoạn code từ onCreate() trong Activity với nội dung sau

Button twoButtonsTitle = (Button) findViewById(R.id.two_buttons); twoButtonsTitle.setOnClickListener(new OnClickListener() { public void onClick(View v) { showDialog(DIALOG_YES_NO_MESSAGE); } }); /* Display a long text message with yes/no buttons and handle each message as well as the cancel action */ Button twoButtons2Title = (Button) findViewById(R.id.two_buttons2); twoButtons2Title.setOnClickListener(new OnClickListener() { public void onClick(View v) { showDialog(DIALOG_YES_NO_LONG_MESSAGE); } }); /* Display a list of items */ Button selectButton = (Button) findViewById(R.id.select_button); selectButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { showDialog(DIALOG_LIST); } });

g. Run ứng dụng

21. Làm việc với Progress Dialog:

a. Tạo new project

b. Định nghĩa const trong Activity

Page 16: Lab 5

ProgressDialog mDialog1; ProgressDialog mDialog2;

private static final int DIALOG1_KEY = 0; private static final int DIALOG2_KEY = 1;

c. Thêm 2 button vào layout.xml

<Button android:id="@+id/showIndeterminate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show" />

<Button android:id="@+id/showIndeterminateNoTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show without title" />

d. Override onCreateDialog(int) trong Activity và thêm đoạn code với nội dung sau

switch (id) { case DIALOG1_KEY: { ProgressDialog dialog = new ProgressDialog(this); dialog.setTitle("Indeterminate"); dialog.setMessage("Please wait while loading..."); dialog.setIndeterminate(true); dialog.setCancelable(true); return dialog; } case DIALOG2_KEY: { ProgressDialog dialog = new ProgressDialog(this); dialog.setMessage("Please wait while loading..."); dialog.setIndeterminate(true); dialog.setCancelable(true); return dialog; } } return null;

e. Thêm đoạn code từ onCreate() trong Activity với nội dung sau

Button button = (Button) findViewById(R.id.showIndeterminate); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showDialog(DIALOG1_KEY); } });

button = (Button) findViewById(R.id.showIndeterminateNoTitle); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showDialog(DIALOG2_KEY); } });

Page 17: Lab 5

f. Run ứng dụng

22. Làm việc với Progress Bar:

a. Tạo mới ứng dụng

b. Tạo vài biến trong Activity

static final int PROGRESS_DIALOG = 0; Button button; ProgressThread progressThread; ProgressDialog progressDialog;

c. Override onCreateDialog(int) trong Activity và thêm đoạn code với nội dung sau

switch(id) { case PROGRESS_DIALOG: progressDialog = new ProgressDialog(this); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage("Loading..."); return progressDialog; default: return null; }

d. Override onPrepareDialog(int) trong Activity và thêm đoạn code với nội dung sau

switch(id) { case PROGRESS_DIALOG: progressDialog.setProgress(0); progressThread = new ProgressThread(handler); progressThread.start(); }

e. Tạo Thread trong Activity với nội dung sau

private class ProgressThread extends Thread { Handler mHandler; final static int STATE_DONE = 0; final static int STATE_RUNNING = 1; int mState; int total; ProgressThread(Handler h) { mHandler = h; } public void run() { mState = STATE_RUNNING; total = 0; while (mState == STATE_RUNNING) { try { Thread.sleep(100);

Page 18: Lab 5

} catch (InterruptedException e) { Log.e("ERROR", "Thread Interrupted"); } Message msg = mHandler.obtainMessage(); msg.arg1 = total; mHandler.sendMessage(msg); total++; } } /* sets the current state for the thread, * used to stop the thread */ public void setState(int state) { mState = state; } }

f. Tạo Handle trong Activity

final Handler handler = new Handler() { public void handleMessage(Message msg) { int total = msg.arg1; progressDialog.setProgress(total); if (total >= 100){ dismissDialog(PROGRESS_DIALOG); progressThread.setState(ProgressThread.STATE_DONE); } } };

g. Trong layout.xml thêm button

<Button android:text="Start" android:id="@+id/progressDialog"android:layout_width="wrap_content"

android:layout_height="wrap_content"></Button>

h. Trong onCreate() thêm vào đoạn code

button = (Button) findViewById(R.id.progressDialog); button.setOnClickListener(new OnClickListener(){ public void onClick(View v) { showDialog(PROGRESS_DIALOG); } });

i. Run ứng dụng

23. Làm việc với Custom View:

a. Tạo mới ứng dụng

b. Trong strings.xml định nghĩa 3 màu nền như drawable

Page 19: Lab 5

<drawable name="red">#7f00</drawable> <drawable name="blue">#770000ff</drawable> <drawable name="green">#7700ff00</drawable>

c. Tạo atts.xml trong thư mục values để định nghĩa thuộc tính của custom View với nội dung sau

<?xml version="1.0" encoding="utf-8"?><resources> <declare-styleable name="LabelView"> <attr name="text" format="string" /> <attr name="textColor" format="color" /> <attr name="textSize" format="dimension" /> </declare-styleable></resources>

d. Tạo mới class LabelView extends từ View

e. Định nghĩa biến trong LabelView

private Paint mTextPaint; private String mText; private int mAscent;

f. Tạo hàm initLabelView trong LabelView với nội dung sau

private final void initLabelView() { mTextPaint = new Paint(); mTextPaint.setAntiAlias(true); mTextPaint.setTextSize(16); mTextPaint.setColor(0xFF000000); setPadding(3, 3, 3, 3); }

g. Tương tự tạo các hàm sau

public void setText(String text) { mText = text; requestLayout(); invalidate();}

public void setTextSize(int size) { mTextPaint.setTextSize(size); requestLayout(); invalidate();}

public void setTextColor(int color) { mTextPaint.setColor(color); invalidate(); Log.i("anvtex","setTextColor");}

Page 20: Lab 5

h. Định nghĩa contructor() cho LabelView

public LabelView(Context context) { super(context); initLabelView();}

public LabelView(Context context, AttributeSet attrs) { super(context, attrs); initLabelView();

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LabelView);

CharSequence s = a.getString(R.styleable.LabelView_text); if (s != null) { setText(s.toString()); }

setTextColor(a.getColor(R.styleable.LabelView_textColor, 0xFF000000));

int textSize = a.getDimensionPixelOffset(R.styleable.LabelView_textSize, 0); if (textSize > 0) { setTextSize(textSize); }}

i. Override onMeasure() với nội dung

@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec));}

j. Định nghĩa measureWidth(int) với nội dung sau

private int measureWidth(int measureSpec) {

int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec);

if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be result = specSize; } else { // Measure the text result = (int) mTextPaint.measureText(mText) + getPaddingLeft() + getPaddingRight(); if (specMode == MeasureSpec.AT_MOST) {

Page 21: Lab 5

// Respect AT_MOST value if that was what is called for by measureSpec result = Math.min(result, specSize); } } return result; }

k. Định nghĩa measureHeight(int) với nội dung sau

private int measureHeight(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec);

mAscent = (int) mTextPaint.ascent(); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be result = specSize; } else { // Measure the text (beware: ascent is a negative number) result = (int) (-mAscent + mTextPaint.descent()) + getPaddingTop() + getPaddingBottom(); if (specMode == MeasureSpec.AT_MOST) { // Respect AT_MOST value if that was what is called for by measureSpec result = Math.min(result, specSize); } } return result; }

l. Override onDraw() với nội dung sau

@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawText(mText, getPaddingLeft(), getPaddingTop() - mAscent, mTextPaint);}

m. Định nghĩa layout.xml với nội dung sau

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res/anhvtex.com" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <anhvtex.com.LabelView android:background="@drawable/red"

Page 22: Lab 5

android:layout_width="wrap_content" android:layout_height="wrap_content" app:text="Red"/> <anhvtex.com.LabelView android:background="@drawable/blue" android:layout_width="wrap_content" android:layout_height="wrap_content" app:text="Blue" app:textSize="20dp"/> <anhvtex.com.LabelView android:background="@drawable/green" android:layout_width="wrap_content" android:layout_height="wrap_content" app:text="Green" app:textColor="#ffffffff" />

</LinearLayout>

n. Run ứng dụng

24. Làm việc với Custom View sử dụng touch sự kiện

a. Tạo new project

b. Thay đổi main.layout xml với nội dung

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Drag the droid around" /> <FrameLayout android:id="@+id/graphics_holder" android:layout_height="match_parent" android:layout_width="match_parent"></FrameLayout></LinearLayout>

c. Tạo biến string trong Activity với tên

private static final String DEBUG_TAG = "GestureFunActivity";d. Tạo mới class với tên PlayAreaView extends View

e. Định nghĩa biến trong lớp này

private GestureDetector gestures; private Matrix translate; private Bitmap droid;

Page 23: Lab 5

f. Trong contructor() bổ sung thêm đoạn code

translate = new Matrix(); gestures = new GestureDetector(GestureFunActivity.this, new GestureListener(this)); droid = BitmapFactory.decodeResource(getResources(), R.drawable.droid_g);

g. Override phương thức onDraw() , thêm đoạn code

canvas.drawBitmap(droid, translate, null); Matrix m = canvas.getMatrix(); Log.d(DEBUG_TAG, "Matrix: " + translate.toShortString()); Log.d(DEBUG_TAG, "Canvas: " + m.toShortString());

h. Override phương thức onTouchEvent() , thêm đoạn code

return gestures.onTouchEvent(event);

i. Định nghĩa 2 phương thức trong class với nội dung

public void onMove(float dx, float dy) { translate.postTranslate(dx, dy); invalidate(); }

public void onResetLocation() { translate.reset(); invalidate(); }

j. Tạo mới class với tên GestureListener implements GestureDetector.OnGestureListener,GestureDetector.OnDoubleTapListener

k. Định nghĩa đối tượng trong class

PlayAreaView view;

l. Trong Contructor() của class thêm vào dòng code

this.view = view;

m. Thêm đoạn code

@Override public boolean onDoubleTap(MotionEvent e) { Log.v(DEBUG_TAG, "onDoubleTap"); view.onResetLocation(); return true; }

@Overridepublic boolean onScroll(MotionEvent e1, MotionEvent e2,

Page 24: Lab 5

float distanceX, float distanceY) {//Log.v(DEBUG_TAG, "onScroll");

view.onMove(-distanceX, -distanceY);return true;

}

n. Chạy ứng dụng

25. Làm việc với Custom Layout

a. Tạo new project

b. Tạo new class extends LinearLayout

c. Định nghĩa biến trong class

private Paint innerPaint, borderPaint ;

d. Trong contructor() gọi init()

e. Định nghĩa hàm init() trong class với nội dung

private void init() {innerPaint = new Paint();innerPaint.setARGB(225, 75, 75, 75); //grayinnerPaint.setAntiAlias(true);

borderPaint = new Paint();borderPaint.setARGB(255, 255, 255, 255);borderPaint.setAntiAlias(true);borderPaint.setStyle(Style.STROKE);borderPaint.setStrokeWidth(2);

}

f. Override phương thức dispatchDraw() với nội dung

@Override protected void dispatchDraw(Canvas canvas) { RectF drawRect = new RectF(); drawRect.set(0,0, getMeasuredWidth(), getMeasuredHeight()); canvas.drawRoundRect(drawRect, 5, 5, innerPaint);

canvas.drawRoundRect(drawRect, 5, 5, borderPaint);

super.dispatchDraw(canvas); }

g. Thay đổi trong layout main.xml với nội dung

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

Page 25: Lab 5

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

android:id="@+id/home_container" android:layout_width="fill_parent" android:layout_height="fill_parent">

<com.google.android.maps.MapViewandroid:id="@+id/city_map_view"

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

android:enabled="true" android:clickable="true" android:apiKey="0DUEIIn35xtmfWC2DXprK5kqNF-

aEaNgRJ4ONxw"/>

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

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

android:orientation="vertical"android:gravity="bottom"android:paddingLeft="5px"android:paddingTop="5px"android:paddingRight="5px">

<com.pocketjourney.view.TransparentPanelandroid:id="@+id/transparent_panel"

android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingTop="5px" android:paddingLeft="5px"

android:paddingBottom="5px"android:paddingRight="5px">

<Button android:id="@+id/button_click_me" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Me!"/>

</com.pocketjourney.view.TransparentPanel>

</LinearLayout></FrameLayout>

h. Thay đổi Activity thành MapActivity, thêm đoạn code trong onCreate()

Button button = (Button) findViewById(R.id.button_click_me); button.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {Toast.makeText(Tutorial1.this, "Button

Clicked",Toast.LENGTH_SHORT).show(); }});

i. Thực hiện quá trình build như trong Lab MapView

Page 26: Lab 5

j. Cài đặt và chạy ứng dung

26. Làm việc với ViewFliper

a. Tạo new project

b. Thay đổi layout main.xml với nội dung

<LinearLayout android:id="@+id/LinearLayout01"android:layout_width="fill_parent"

android:layout_height="fill_parent"xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"><LinearLayout android:id="@+id/LinearLayout03"

android:layout_width="wrap_content" android:layout_height="wrap_content">

<Button android:id="@+id/Button01" android:layout_width="wrap_content"

android:layout_height="wrap_content" android:text="Next"></Button>

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

android:layout_height="wrap_content" android:text="Previous"></Button>

</LinearLayout>

<LinearLayout android:id="@+id/LinearLayout02"android:layout_width="wrap_content"

android:layout_height="wrap_content"><ViewFlipper android:id="@+id/ViewFlipper01"

android:layout_width="wrap_content" android:layout_height="wrap_content">

<!--adding views to ViewFlipper --><TextView android:id="@+id/TextView01"

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

android:text="Flipper Content 1"></TextView><TextView android:id="@+id/TextView02"

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

android:text="Flipper Content 2"></TextView><TextView android:id="@+id/TextView03"

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

android:text="Flipper Content 3"></TextView></ViewFlipper>

</LinearLayout>

</LinearLayout>

c. Trong Activity implement sự kiện onClickListener và định nghĩa biến

Button next;Button previous;

Page 27: Lab 5

ViewFlipper vf;

d. Thêm đoạn code trong onCreate() của Activity

vf = (ViewFlipper) findViewById(R.id.ViewFlipper01); next = (Button) findViewById(R.id.Button01); previous = (Button) findViewById(R.id.Button02); next.setOnClickListener(this); previous.setOnClickListener(this);

e. Override phương thức onClick() và thêm đoạn code

if (v == next) {

vf.showNext();}if (v == previous) {

vf.showPrevious();}

f. Chạy ứng dụng