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:
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
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
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
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
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
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
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
c. Thêm 2 button vào layout.xml
switch (id) { case DIALOG1_KEY: { ProgressDialog dialog = new ProgressDialog(this);
d. Override onCreateDialog(int) trong Activity và thêm đoạn code với nội dung sau
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 16
Ver 1.0 – 2016, FIT - HCMUP
Lab 06: GridView abd Other Control
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;
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); } });
e. Thêm đoạn code từ onCreate() trong Activity với nội dung sau
f. Run ứng dụng
2.8 Làm việc với Progress Bar:
a. Tạo mới ứng dụng
static final int PROGRESS_DIALOG = 0; Button button; ProgressThread progressThread; ProgressDialog progressDialog;
b. Tạo vài biến trong Activity
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 17
Ver 1.0 – 2016, FIT - HCMUP
Lab 06: GridView abd Other Control
switch(id) { case PROGRESS_DIALOG: progressDialog = new ProgressDialog(this); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage("Loading..."); return progressDialog; default: return null; }
c. Override onCreateDialog(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(); }
d. Override onPrepareDialog(int) trong Activity và thêm đoạn code với nội dung sau
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); } catch (InterruptedException e) { Log.e("ERROR", "Thread Interrupted"); }
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 18
Ver 1.0 – 2016, FIT - HCMUP
Lab 06: GridView abd Other Control
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
android:layout_height="wrap_content">
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