Ver 1.0 – 2016, FIT - HCMUP

Lab 06: GridView abd Other Control

1 GridView

GridView là một viewgroup, nó hiển thị các phần tử con trên một lưới cuộn 2 chiều.

Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 1

Ver 1.0 – 2016, FIT - HCMUP

Lab 06: GridView abd Other Control

1.1 GridItem

Một GridView được tạo từ một danh sách các GridItem. GridItem là một ô (cell) riêng lẻ trong gridview nơi mà dữ liệu sẽ được hiển thị. Bất kỳ dữ liệu nào trong GridView chỉ được hiển thị thông qua GridItem.

Một GridItem là một mảnh giao diện, nó có thể được làm bởi một số View.

1.2 Ví dụ GridView với ArrayAdapter

1.2.1 Tạo giao diện

Tạo mới một Android project có tên SimpleGridView.

 columnWidth: 120  gravity

o center:  numColumns: auto_fit

Thiết kế giao diện và thay đổi các thuộc tính GridView

Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 2

Ver 1.0 – 2016, FIT - HCMUP

Lab 06: GridView abd Other Control

1.2.2 Thiết kế lớp Website tương ứng một item

public class Website { private String name; private String url; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public String toString() { return name; } public Website(String name, String url) { this.name = name; this.url = url; } } 1.2.3 Gắn hàm xử lý trong ActivityMain

android.R.layout.simple_list_item_1 , websitelist); final GridView gridView = (GridView)findViewById(R.id.gridView); ArrayList websitelist = new ArrayList(); websitelist.add(new Website("Google", "http://google.com.vn")); websitelist.add(new Website("FIT, HCMUE", "http://fit.hcmup.edu.vn")); websitelist.add(new Website("HCMUE", "http://hcmup.edu.vn")); websitelist.add(new Website("HIENLTH", "http://fit.hcmup.edu.vn/~hienlth")); websitelist.add(new Website("Tuổi trẻ", "http://tuoitre.vn")); websitelist.add(new Website("Zing News", "http://zing.vn")); ArrayAdapter arrayAdapter = new ArrayAdapter(this, gridView.setAdapter(arrayAdapter);

Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 3

Ver 1.0 – 2016, FIT - HCMUP

Lab 06: GridView abd Other Control

gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { Website website = (Website) gridView.getItemAtPosition(position); Toast.makeText(MainActivity.this, "Vừa chọn :" + " " + website.getName() + "\n(" + website.getUrl() + ")",Toast.LENGTH_LONG).show(); } }); 1.2.4 Kết quả chạy chương trình:

1.3 Tạo GridView với Layout tùy chỉnh

1.3.1 Tạo mới Layout cho GridView Item:

Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 4

Ver 1.0 – 2016, FIT - HCMUP

Lab 06: GridView abd Other Control

Tên file giao diện: my_item.xml

Phần code xml:

Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 5

Ver 1.0 – 2016, FIT - HCMUP

Lab 06: GridView abd Other Control

1.3.2 Chuẩn bị hình ảnh và copy vào thư mục drawable

1.3.3 Tạo class quản lý một item

public class Country { private String countryName; private String flagName; private int population; public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } public String getFlagName() { return flagName; } public void setFlagName(String flagName) { this.flagName = flagName; } public int getPopulation() { return population; } public void setPopulation(int population) { this.population = population; } public Country(String countryName, String flagName, int population) { this.countryName = countryName;

Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 6

Ver 1.0 – 2016, FIT - HCMUP

Lab 06: GridView abd Other Control

this.flagName = flagName; this.population = population; } @Override public String toString() { return this.countryName+" (Dân số: "+ this.population+")"; } } 1.3.4 Tạo lớp tùy chỉnh kế thừa từ BaseAdapter Trong lớp này có sử dụng ViewHolder:

static class ViewHolder { ImageView flagView; TextView countryNameView; TextView populationView; }

Mục đích của việc này là giúp ta sử dụng lại được biến convertView, giảm thiểu lại số lần gọi findViewById không cần thiết, giúp nó chạy mượt mà hơn.

@Override

Trong hàm getView ta viết lại như sau:

public View getView(int position, View convertView, ViewGroup parent) {

ViewHolder holder;

if (convertView == null) {

convertView = layoutInflater.inflate(R.layout.my_item, null);

holder = new ViewHolder();

holder.flagView = (ImageView) convertView.findViewById(R.id.imageView_flag);

holder.countryNameView = (TextView)

convertView.findViewById(R.id.textView_countryName);

holder.populationView = (TextView)

convertView.findViewById(R.id.textView_population);

convertView.setTag(holder);

} else {

holder = (ViewHolder) convertView.getTag();

}

//set data

Country country = this.listData.get(position);

holder.countryNameView.setText(country.getCountryName());

Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 7

Ver 1.0 – 2016, FIT - HCMUP

Lab 06: GridView abd Other Control

holder.populationView.setText("" + country.getPopulation());

int imageId = this.getMipmapResIdByName(country.getFlagName());

holder.flagView.setImageResource(imageId);

return convertView; } Chi tiết lớp CustomGridViewAdapter như sau:

public class CustomGridAdapter extends BaseAdapter { static class ViewHolder { ImageView flagView; TextView countryNameView; TextView populationView; } private List listData; private LayoutInflater layoutInflater; public CustomGridAdapter(Context context, LayoutInflater layoutInflater, List listData) { this.context = context; this.layoutInflater = layoutInflater; this.listData = listData; } public CustomGridAdapter(Context aContext, List listData) { this.context = aContext; this.listData = listData; layoutInflater = LayoutInflater.from(aContext); } private Context context; @Override public int getCount() { return listData.size(); } @Override public Object getItem(int position) { return listData.get(position); } @Override public long getItemId(int position) {

Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 8

Ver 1.0 – 2016, FIT - HCMUP

Lab 06: GridView abd Other Control

return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = layoutInflater.inflate(R.layout.my_item, null); holder = new ViewHolder(); holder.flagView = (ImageView) convertView.findViewById(R.id.imageView_flag); holder.countryNameView = (TextView) convertView.findViewById(R.id.textView_countryName); holder.populationView = (TextView) convertView.findViewById(R.id.textView_population); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } Country country = this.listData.get(position); holder.countryNameView.setText(country.getCountryName()); holder.populationView.setText("" + country.getPopulation()); int imageId = context.getResources().getIdentifier(country.getFlagName(), "drawable", context.getPackageName()); holder.flagView.setImageResource(imageId); return convertView; } } 1.3.5 Xử lý trong Activity

List mylist = new ArrayList(); mylist.add(new Country("Việt Nam", "vi", 98000000)); mylist.add(new Country("Anh", "en", 64000000)); mylist.add(new Country("Ý", "it", 62000000)); mylist.add(new Country("Mỹ", "us", 323000000)); mylist.add(new Country("Úc", "au", 23766305)); mylist.add(new Country("Nhật", "jp", 126788677)); mylist.add(new Country("Đức", "ge", 81000000)); mylist.add(new Country("Pháp", "fr", 66300000)); mylist.add(new Country("Nga", "ru", 142000000)); gridView.setAdapter(new CustomGridViewAdapter(this, mylist)); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { Country country = (Country) gridView.getItemAtPosition(position); Toast.makeText(MainActivity.this, "Vừa chọn :" + " " + country,

Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 9

Ver 1.0 – 2016, FIT - HCMUP

Lab 06: GridView abd Other Control

Toast.LENGTH_LONG).show(); } }); 1.3.6 Chạy và thử nghiệm

2 Làm việc với các control khác

2.1 WebView

Xem link: http://developer.android.com/resources/tutorials/views/hello-webview.html

Mở rộng bài tập GridView đơn giản dùng WebView để hiển thị trang web có địa chỉ được chọn.

public void onItemClick(AdapterView parent, View view, int position, long id) { Website website = (Website) gridView.getItemAtPosition(position); webView.getSettings().setLoadsImagesAutomatically(true); webView.getSettings().setJavaScriptEnabled(true); webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 10

Ver 1.0 – 2016, FIT - HCMUP

Lab 06: GridView abd Other Control

webView.loadUrl(website.getUrl()); }

2.2 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:

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

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

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

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

Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 11

Ver 1.0 – 2016, FIT - HCMUP

Lab 06: GridView abd Other Control

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", "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",

Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 12

Ver 1.0 – 2016, FIT - HCMUP

Lab 06: GridView abd Other Control

"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

2.3 Làm việc với DatePicker, TimePicker

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

datepicker.html

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

timepicker.html

2.4 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

b. Run ứng dụng

2.5 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 node

Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 13

Ver 1.0 – 2016, FIT - HCMUP

Lab 06: GridView abd Other Control

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

d. Trong layout.xml file sử dụng com.google.android.maps.MapView như node chính

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.

@Override protected 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

Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 14

Ver 1.0 – 2016, FIT - HCMUP

Lab 06: GridView abd Other Control

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

2.6 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

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

android:layout_height="wrap_content" android:id="@+id/button1" android:text="Show Toast">

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

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

// TODO Auto-generated method stub ShowNotification(); @Override public void onClick(View v) { } });

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";

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

Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 15

Ver 1.0 – 2016, FIT - HCMUP

Lab 06: GridView abd Other Control

Intent notificationIntent = new Intent(this, NotificationActivity.class); 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

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

a. Tạo new project

ProgressDialog mDialog1; ProgressDialog mDialog2; private static final int DIALOG1_KEY = 0; private static final int DIALOG2_KEY = 1;

b. Định nghĩa const trong Activity

android:layout_width="wrap_content" android:text="Previous"> android:layout_height="wrap_content"> android:layout_height="wrap_content"> android:layout_width="wrap_content" android:text="Flipper Content 1"> android:layout_width="wrap_content" android:text="Flipper Content 2"> android:layout_width="wrap_content" android:text="Flipper Content 3">

Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 24

Ver 1.0 – 2016, FIT - HCMUP

Lab 06: GridView abd Other Control

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

Button next; Button previous; ViewFlipper vf;

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

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

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

vf.showPrevious(); if (v == next) { vf.showNext(); } if (v == previous) { } f. Chạy ứng dụng

Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 25