lab 06: gridview and other control€¦ · ver 1.0 – 2016, fit - hcmup lab 06: gridview and other...
TRANSCRIPT
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 1
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.
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 2
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.
Thiết kế giao diện và thay đổi các thuộc tính GridView
columnWidth: 120
gravity
o center: <check>
numColumns: auto_fit
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 3
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
final GridView gridView = (GridView)findViewById(R.id.gridView);
ArrayList<Website> websitelist = new ArrayList<Website>();
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<Website> arrayAdapter = new ArrayAdapter<Website>(this,
android.R.layout.simple_list_item_1 , websitelist);
gridView.setAdapter(arrayAdapter);
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 4
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:
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 5
Tên file giao diện: my_item.xml
Phần code xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:id="@+id/imageView_flag" />
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Country Name"
android:id="@+id/textView_countryName" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Population"
android:id="@+id/textView_population"
android:layout_gravity="center_vertical" />
</LinearLayout>
</LinearLayout>
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 6
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;
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 7
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.
Trong hàm getView ta viết lại như sau:
@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();
}
//set data
Country country = this.listData.get(position);
holder.countryNameView.setText(country.getCountryName());
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 8
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<Country> listData;
private LayoutInflater layoutInflater;
public CustomGridAdapter(Context context, LayoutInflater layoutInflater, List<Country> listData) {
this.context = context;
this.layoutInflater = layoutInflater;
this.listData = listData;
}
public CustomGridAdapter(Context aContext, List<Country> 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) {
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 9
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<Country> mylist = new ArrayList<Country>();
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,
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 10
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);
webView.loadUrl(website.getUrl());
}
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 11
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:
<?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:
<?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",
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 12
"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", "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
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 13
2.3 Làm việc với DatePicker, TimePicker
Tham khảo thêm link:
http://developer.android.com/resources/tutorials/views/hello-datepicker.html
http://developer.android.com/resources/tutorials/views/hello-timepicker.html
a. Tạo project mới version 4.0.
b. Tạo giao diện có 2 button , trong java ánh xạ 2 button với tên bt1, bt2.
c. Khai báo thêm biến toàn cục như sau:
Calendar lich=Calendar.getInstance();
d. Viết một hàm (ngoài onCreate, cùng cấp onCreate)
void my_time_dialog()
{
TimePickerDialog tpdialog=new TimePickerDialog(
this,
new OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int
minute) {
// TODO Auto-generated method stub
bt2.setText(hourOfDay+"/"+minute);
}
},
lich.get(Calendar.HOUR),
lich.get(Calendar.MINUTE),
false);
tpdialog.show();
}
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 14
e. Viết tiếp 1 hàm giống hàm trên như sau:
void my_date_dialog()
{
DatePickerDialog dpdialog=new DatePickerDialog(this,
new OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
bt1.setText(dayOfMonth+"/"+(monthOfYear+1)+"/"+year);
}
},
lich.get(Calendar.YEAR),
lich.get(Calendar.MONTH),
lich.get(Calendar.DAY_OF_MONTH));
dpdialog.show();
}
f. Trong onCreate bắt sự kiện cho 2 button
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
my_date_dialog();
}
});
bt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
my_time_dialog();
}
});
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
<?xml version="1.0" encoding="utf-8"?>
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 15
<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
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 <application> node
<uses-library android:name="com.google.android.maps" />
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.
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 16
@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
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
<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() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ShowNotification();
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 17
}
});
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);
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
b. Định nghĩa const trong Activity
ProgressDialog mDialog1;
ProgressDialog mDialog2;
private static final int DIALOG1_KEY = 0;
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 18
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);
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 19
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG2_KEY);
}
});
f. Run ứng dụng
2.8 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;
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 20
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");
}
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"
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 21
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
2.9 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;
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 22
private Bitmap droid;
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();
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 23
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
//Log.v(DEBUG_TAG, "onScroll");
view.onMove(-distanceX, -distanceY);
return true;
}
n. Chạy ứng dụng
2.10 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); //gray
innerPaint.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());
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 24
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"?>
<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.MapView
android: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.TransparentPanel
android: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"
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 25
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
j. Cài đặt và chạy ứng dụng
2.11 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"
Ver 1.0 – 2016, FIT - HCMUP Lab 06: GridView and Other Control
Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 26
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;
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