LAB ANDROID NGUYEN HA GIANG 2012

82 425 4
LAB ANDROID  NGUYEN HA GIANG 2012

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Lập trình tảng Android Khoa CNTT - Hutech ĐẠI HỌC KỸ THUẬT CÔNG NGHỆ (HUTECH) KHOA CÔNG NGHỆ THÔNG TIN ==oOo== Người soạn: ThS Nguyễn Hà Giang Email: nguyenha.giang@yahoo.com Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) Lập trình tảng Android Khoa CNTT - Hutech Lab 1: Ứng dụng Android Mục tiêu Làm quen với cách thức tạo ứng dụng Android dùng IDE Eclipse Hiểu cấu trúc Android project Dùng XML để tạo layout Activity Quen với việc sử dụng resource ứng dụng Android Yêu cầu Đã cài đặt môi trường đầy đủ để xây dựng ứng dụng Android Eclipse Có số kiến thức lập trình Android Hướng dẫn Bước 1: Tạo ứng dụng Android từ Eclipse Trong Eclipse chọn Alt +Shift + N ( New project), chọn tiếp Android Project Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) Lập trình tảng Android Khoa CNTT - Hutech Hình 1.1: Minh hoạ cách tạo Android Project Sau khai báo thông tin để tạo Android project chọn Finish để hoàn tất Eclipse tạo project Android có cấu trúc sau: Hình 1.2: Toàn Android project ban đầu Eclipse phát sinh Ứng dụng có thành phần gọi Activity có tên FirstAppAndroidActivity, ứng dụng Android, activity thành phần GUI chứa widget (tương tự control windows form) Nói cách tổng quát ứng dụng có tương tác với người dùng thông qua UI phải có activity, ứng dụng Android tạo nhiều Activity (giống tạo nhiều form lập trình desktop) Trong Activity FirstAppAndroidActivity có phương thức override onCreate phương thức dùng để khởi tạo thành phần UI xử lý activity Trong phương thức có gọi hàm setContentView truyền vào id layout khai báo thư mục res/layout Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) Lập trình tảng Android Khoa CNTT - Hutech Hình 1.3: File XML Layout chứa mô tả giao diện activity Giải thích file mô tả layout main.xml activity: Bao gồm LinearLayout, dạng ViewGroup cho phép chứa View bên xếp theo hai dạng: “vertical” hay “horizontal” Trong layout LinearLayout thiết lập theo phương dọc, giá trị fill_parent cho biết layout chiếm hết kích thước thành phần bao chứa (full kích thước) Một TextView dạng tương tự Label Windows Form, cho phép hiển thị nội dung thông tin đó, TextView thiết lập có kích thước ngang kích thước thành phần bao chứa, kích thước dài wrap, vừa đủ hiển thị nội dung Thuộc tính android:text thiết lập chuỗi cần hiển thị TextView, phần khai báo chuỗi @string/hello có ý nghĩa lấy chuỗi tên hello khai báo phần resource file strings.xml, nội dung (giá trị) chuỗi hello hiển thị lên TextView Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) Lập trình tảng Android Khoa CNTT - Hutech Hình 1.4: File strings.xml chứa định nghĩa chuỗi File strings.xml chứa định nghĩa liên quan đến chuỗi, lập trình Android nên sử dụng file để định nghĩa chuỗi chương trình Java hay phần layout tham chiếu đến chuỗi Cách truy xuất chuỗi khai báo strings.xml mô tả hình Hình 1.5: Mô tả cách thức tham chiếu đến chuỗi java code XML layout Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) Lập trình tảng Android Khoa CNTT - Hutech Bước 2: Biên dịch chạy ứng dụng ta kết emulator sau: Hình 1.6: Ứng dụng chạy emulator Bước 3: Modify lại chương trình để hiển thị thông báo sau: “Đây chương trình Android tôi” Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) Lập trình tảng Android Khoa CNTT - Hutech Hình 1.7: Ứng dụng sau modify lại chuỗi Bước 4: làm quen với thuộc tính TextView, thiết lập thuộc tính cho TextView theo bảng sau (thiết lập file layout xml) Thiết lập thuộc tính cho TextView file layout XML textSize 30dp textColor #ff5500 textStyle bold gravity center shadowColor #e6b121 shadowRadius 1.5 shadowDx shadowDy Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) Lập trình tảng Android Khoa CNTT - Hutech Kết activity sau (trong demo thay đổi text TextView “Hello Android”: Hình 1.8: Kết sau thiết lập thuộc tính TextView Trong phần khai báo màu textColor shadowColor ta dùng số màu, việc dùng trực tiếp khó hiểu (khi nhìn vào mã hexa màu gì), ta làm cách khác dễ hiểu cách tạo file resource định nghĩa bảng màu Trong Android cho phép làm điều cách khai báo file colors.xml hình minh hoạ sau: Trong file ta định nghĩa hai màu sau: #ff5500 #e6b121 Khi tham chiếu layout dùng cú pháp sau Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) Lập trình tảng Android Khoa CNTT - Hutech Thiết lập thuộc tính cho TextView file layout XML textColor @color/orange shadowColor @color/gold Hình 1.9: Màn hình bổ sung file định nghĩa số màu resource Bước 5: thêm hình vào linearlayout Import hình vào project, (cách thức import hướng dẫn phần lab J2ME) Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) Lập trình tảng Android Khoa CNTT - Hutech Hình 1.10: Import hình làm ảnh vào project Khai báo hình cho LinearLayout sau Kết ứng dụng sau: (đã đổi nội dung TextView “Welcome to Lăng Cô Beach” Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) 10 Lập trình tảng Android Khoa CNTT - Hutech Activity tổng quát Bổ sung phần mã lệnh để TabHost sử dụng nội dung FrameLayout chia thành tab khác Các bước thực bao gồm  Thêm phần import android.app.TabActivity android.widget.TabHost  Thay đổi phần kế thừa LunchList từ Activity sang TabActivity Hình 7.1: Bổ sung cho lớp LuchList  Sử dụng icon có kích thước 32x32 làm icon cho tab Filename Thể list.png restaurant.png Hình 7.2: Import hai icon vào project Phần code bổ sung cho onCreate() thay đổi sau: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) 68 Lập trình tảng Android Khoa CNTT - Hutech setContentView(R.layout.activity_lunch_list); Button save = (Button) findViewById(R.id.save); save.setOnClickListener(onSave); ListView list = (ListView)findViewById(R.id.restaurants); adapter = new RestaurantAdapter(); list.setAdapter(adapter); // Phần bổ sung cho Tab TabHost.TabSpec spec = getTabHost().newTabSpec("tag1"); spec.setContent(R.id.restaurants); spec.setIndicator("List",getResources().getDrawable(R.drawable.list)); getTabHost().addTab(spec); spec = getTabHost().newTabSpec("tag2"); spec.setContent(R.id.details); spec.setIndicator("Details", getResources().getDrawable(R.drawable.restaurant)); getTabHost().addTab(spec); getTabHost().setCurrentTab(0); }// end onCreate Biên dịch chạy ứng dụng! Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) 69 Lập trình tảng Android Khoa CNTT - Hutech Hình 7.3: Tab list hiển thị danh sách nhà hàng Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) 70 Lập trình tảng Android Khoa CNTT - Hutech Hình 7.4: Tab details cho phép nhập thông tin nhà hàng Bước 3: Bổ sung chức cho phép user chọn nhà hàng tab list thông tin nhà hàng chọn hiển thị tab details Thực theo bước sau:  Import android.widget.AdapterView vào lớp activity Hình 7.5: Import thư viện AdapterView Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) 71 Lập trình tảng Android Khoa CNTT - Hutech  Tạo biến AdapterView.OnItemClickListener tên onListClick lớp LunchList Hình 7.6: Khai báo OnItemClickListener  Thiết lập OnItemClickListener cho ListView onCreate() activity Hình 7.7: Thiết lập OnItemClickListener cho ListView Bước 4: Viết phần xử lý cho Item Click Listener ListView, phần code lấy item chọn (dùng position) ListView thông qua adapter Thiết lập thông tin từ item chọn bao gồm: {tên nhà hàng, địa chỉ, kiểu} lên tab details private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView parent, View view, int position, long id) { Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) 72 Lập trình tảng Android Khoa CNTT - Hutech // TODO Auto-generated method stub Restaurant r = listRestaurant.get(position); // lấy item chọn EditText name; EditText address; RadioGroup types; // Tham chiếu đến view details name = (EditText)findViewById(R.id.name); address = (EditText)findViewById(R.id.addr); types = (RadioGroup)findViewById(R.id.types); // thiết lập thông tin tương ứng name.setText(r.getName()); address.setText(r.getAddress()); if (r.getType().equals("Sit down")) types.check(R.id.sit_down); else if (r.getType().equals("Take out")) types.check(R.id.take_out); else types.check(R.id.delivery); // sinh viên bổ sung lệnh sau để chuyển view tab details getTabHost().setCurrentTab(1); } }; Bước 5: Biên dịch chạy ứng dụng LunchList Version 4! =oOo= Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) 73 Lập trình tảng Android Khoa CNTT - Hutech Lab 8: Lunch List Application Version (*) (*): Tham khảo từ AndroidTM Programming Tutorials, version 3.2 for Android 3.0, Mark L Murphy, 2011, CommonsWare Mục tiêu Nâng cấp phiên Lunch List App Version với chức lưu trữ Làm quen với cách thức lưu trữ liệu dùng SQLite Cách thức khai báo tạo database SQLite Tìm hiểu cách truy vấn liệu từ table SQLite trả kết liệu đối tượng Cursor Sử dụng Cursor CursorAdapter để duyệt hiển thị nội dung row liệu lên view ListView Yêu cầu Hoàn thành phần code lab Nội dung Bước 1: Tạo lớp chứa code hỗ trợ để thao tác database SQLite, bao gồm tên database schema cho table Lớp có tên RestaurantHelper kế thừa từ lớp sở SQLiteOpenHelper import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class RestaurantHelper extends SQLiteOpenHelper { // khai báo tên database schema private static final String DATABASE_NAME = "lunchlist.db"; private static final int SCHEMA_VERSION = 1; // Bổ sung constructor chứa tham số kiểu Context public RestaurantHelper(Context context) { // gọi constructor SQLiteOpenHelper truyền tên database chema Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) 74 Lập trình tảng Android Khoa CNTT - Hutech super(context, DATABASE_NAME, null, SCHEMA_VERSION); } public RestaurantHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } }// end RestaurantHelper Bước 2: Tạo bảng liệu để lưu trữ thông tin nhà hàng, phần code tạo bảng liệu thực thi phương thức onCreate() @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL("CREATE TABLE restaurants (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, address TEXT, type TEXT);"); } Đoạn code tạo bảng restaurants với cấu trúc mô tả gồm id, name, address, type Bước 3: Do RestaurantHelper cầu nối để truy cập CSDL, activity LunchList phải có đối tượng RestaurantHelper để truy cập liệu thêm nội dung Các thao tác bao gồm open CSDL sau hoàn tất phần xử lý liên quan đến liệu close CSDL  Bước 3.1: tạo biến liệu thành viên helper LunchList public class LunchList extends TabActivity { Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) 75 Lập trình tảng Android Khoa CNTT - Hutech // khai bao danh sach restaurant List listRestaurant = new ArrayList(); RestaurantAdapter adapter = null; // khai bao bien vien lien quan den truy cap du lieu RestaurantHelper helper;  Bước 3.2: khởi tạo đối tượng cho helper phương thức onCreate LunchList, lưu ý phần khởi tạo phải viết sau gọi setContentView() @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lunch_list); // khoi tao doi duong RestaurantHelper helper = new RestaurantHelper(this);  Bước 3.3: override phương thức onDestroy LunchList để đóng CSDL @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); // Đóng sở liệu helper.close(); }// end onDestroy  Bước 4: Lưu trữ thông tin nhà hàng vào CSDL Bổ sung số phần xử lý hỗ trợ thêm liệu vào CSDL  Bước 4.1: tạo phương thức insert RestaurantHelper sau: // phuong thuc insert mot dong thong tin nha hang public void insert(String name, String address, String type) { // tao doi tuong du lieu ContentValue ContentValues cv = new ContentValues(); // dua cac du lieu vao theo tung cap ten field va value cv.put("name", name); cv.put("address",address); Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) 76 Lập trình tảng Android Khoa CNTT - Hutech cv.put("type", type); // yeu cau SQLiteDatabase insert du lieu vao database getWritableDatabase().insert("restaurants", "name", cv); }  Bước 4.2: gọi phương thức insert chức onSave LunchList private View.OnClickListener onSave = new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub Restaurant restaurant = new Restaurant(); // lay thong tin ve editText; EditText name = (EditText)findViewById(R.id.name); EditText address = (EditText)findViewById(R.id.addr); restaurant.setName(name.getText().toString()); restaurant.setAddress(address.getText().toString()); RadioGroup types = (RadioGroup)findViewById(R.id.types); // kiem tra xem user chon loai nao switch (types.getCheckedRadioButtonId()) { case R.id.take_out: restaurant.setType("Take out"); break; case R.id.sit_down: restaurant.setType("Sit down"); break; case R.id.delivery: restaurant.setType("Delivery"); break; default: break; } // them vao CSDL helper.insert(restaurant.getName(), restaurant.getAddress(), restaurant.getType()); } }; Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) 77 Lập trình tảng Android Khoa CNTT - Hutech Bước 5: lấy danh sách restaurant từ CSDL Trong bước trước ta thêm liệu restaurant vào CSDL Tiếp theo ta viết code để lấy liệu CSDL Do đó, bổ sung thêm phần xử lý để truy vấn liệu trả đối tượng Cursor với cấu trúc cột bảng restaurants đối tượng Cursor Android tương tự với cursor thư viện truy cập CSDL ngôn ngữ khác Cụ thể ta bổ sung thêm phương thức getAll(), phương thức gọi phương thức rawQuery() SQLiteDatabase Truyền câu truy vấn thích hợp vào phương thức rawQuery() để lấy liệu // phuong thuc truy van toan bo du lieu public Cursor getAll() { Cursor cur; cur = getReadableDatabase().rawQuery("SELECT _id, name, address, type FROM restaurants ORDER BY name", null); return (cur); } Để thuận tiện cho việc truy cập trường liệu Cursor ta bổ sung thêm phương thức kiểu getter để lấy liệu tương ứng dòng liệu từ Cursor, phần khai báo phương thức getter lớp RestaurantHelper public String getName(Cursor c) { // truy cap cot thu la cot name return (c.getString(1)); } public String getAddress(Cursor c) { // truy cap cot thu la cot address return (c.getString(2)); } public String getType(Cursor c) { // truy cap cot thu la type return (c.getString(3)); } Bước 6: Thay đổi Adapter để sử dụng Cursor Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) 78 Lập trình tảng Android Khoa CNTT - Hutech Trong phiên trước lớp RestaurantAdapter kế thừa từ ArrayAdapter không thích hợp với Cursor Do phần ta thay đổi để RestaurantAdapter xử lý tốt với Cursor Chính xác thay đổi lớp kế thừa từ ArrayAdapter sang CursorAdapter ArrayAdapter tạo view cho item array hay list Trong CursorAdapter tạo view cho dòng Cursor  Bước 6.1: Tạo lớp RestaurantAdapter với thay đổi sau class RestaurantAdapter extends CursorAdapter { public RestaurantAdapter(Cursor c) { super(LunchList.this, c); } public RestaurantAdapter(Context context, Cursor c) { super(context, c); // TODO Auto-generated constructor stub } @Override public void bindView(View view, Context context, Cursor cursor) { // TODO Auto-generated method stub View row = view; ((TextView)row.findViewById(R.id.title)) setText(helper.getName(cursor)); ((TextView)row.findViewById(R.id.address)) setText(helper.getAddress(cursor)); ImageView icon = (ImageView)row.findViewById(R.id.icon); String type = helper.getType(cursor); if (type.equals("Take out")) icon.setImageResource(R.drawable.icon_t); else if (type.equals("Sit down")) icon.setImageResource(R.drawable.icon_s); else icon.setImageResource(R.drawable.icon_d); }// end bindView @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { // TODO Auto-generated method stub LayoutInflater inflater = getLayoutInflater(); View row = inflater.inflate(R.layout.row, parent, false); Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) 79 Lập trình tảng Android Khoa CNTT - Hutech return row; } }// end class RestaurantAdapter  Bước 6.2: Bổ sung lại phần khai báo lớp LunchList cho phù hợp với thay đổi Bao gồm thay đổi kiểu liệu listRestaurant từ ArrayList sang Cursor đổi tên từ listRestaurant sang curRestaurant (cho thích hợp) public class LunchList extends TabActivity { // khai bao danh sach restaurant dung Cursor Cursor curRestaurant = null; RestaurantAdapter adapter = null; // khai bao bien vien lien quan den truy cap du lieu RestaurantHelper helper = null;  Bước 6.3: Bổ sung phần code lấy liệu từ CSDL đưa vào Cursor tạo adapter phương thức onCreate() activity LunchList @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lunch_list); // khoi tao doi duong RestaurantHelper helper = new RestaurantHelper(this); Button save = (Button) findViewById(R.id.save); save.setOnClickListener(onSave); ListView list = (ListView)findViewById(R.id.restaurants); list.setOnItemClickListener(onListClick); // lay du lieu tu CSDL curRestaurant = helper.getAll(); startManagingCursor(curRestaurant); adapter = new RestaurantAdapter(curRestaurant); list.setAdapter(adapter); TabHost.TabSpec spec = getTabHost().newTabSpec("tag1"); spec.setContent(R.id.restaurants); spec.setIndicator("List",getResources().getDrawable(R.drawable.list)); Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) 80 Lập trình tảng Android Khoa CNTT - Hutech getTabHost().addTab(spec); spec = getTabHost().newTabSpec("tag2"); spec.setContent(R.id.details); spec.setIndicator("Details", getResources().getDrawable(R.drawable.restaurant)); getTabHost().addTab(spec); getTabHost().setCurrentTab(0); } Bước 7: xóa tham chiếu ArrayList code phần trước Do phần code ArayList không làm việc với Cursor Cụ thể đối tượng listener onListClick cần phải di chuyển Cursor đến vị trí position để lấy vị trí item chọn private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView parent, View view, int position, long id) { // di chuyển cursor đến vị trí position curRestaurant.moveToPosition(position); EditText name; EditText address; RadioGroup types; name = (EditText)findViewById(R.id.name); address = (EditText)findViewById(R.id.addr); types = (RadioGroup)findViewById(R.id.types); // sử dụng đối tượng helper để lấy thông tin nhà hàng name.setText(helper.getName(curRestaurant)); address.setText(helper.getAddress(curRestaurant)); if (helper.getType(curRestaurant).equals("Sit down")) types.check(R.id.sit_down); else if (helper.getType(curRestaurant).equals("Take out")) types.check(R.id.take_out); else types.check(R.id.delivery); // chuyen qua tab detail getTabHost().setCurrentTab(1); } }; Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) 81 Lập trình tảng Android Khoa CNTT - Hutech Bước 8: Refesh lại danh sách sau thực thi phần insert private View.OnClickListener onSave = new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub Restaurant restaurant = new Restaurant(); // tham chieu den cac view layout EditText name = (EditText)findViewById(R.id.name); EditText address = (EditText)findViewById(R.id.addr); RadioGroup types = (RadioGroup)findViewById(R.id.types); restaurant.setName(name.getText().toString()); restaurant.setAddress(address.getText().toString()); // kiem tra xem user chon loai nao switch (types.getCheckedRadioButtonId()) { case R.id.take_out: restaurant.setType("Take out"); break; case R.id.sit_down: restaurant.setType("Sit down"); break; case R.id.delivery: restaurant.setType("Delivery"); break; default: break; } // them vao CSDL helper.insert(restaurant.getName(), restaurant.getAddress(), restaurant.getType()); // refesh lai du lieu curRestaurant.requery(); }// end onClick }; // end View.OnClickListener Bước 9: Biên dịch chạy chương trình =oOo= Nguyễn Hà Giang – (nguyenha.giang@yahoo.com) 82 [...]... android: layout_height="wrap_content" android: id="@+id/textView1" android: textAppearance=" ?android: attr/textAppearanceMedium" android: text="@string/forecolor" android: layout_width="wrap_content"> Giải thích: EditText android: id="@+id/EditText01" Khai báo id của EditText android: hint="Nhập... android: layout_height="wrap_content" android: layout_span="2" android: entries="@array/color_name_array"> ... chọn New -> Android XML File Hình 1.16: Tạo file XML layout cho SecondActivity File second.xml ban đầu có mô tả như sau Nguyễn Hà Giang – (nguyenha .giang@ yahoo.com) 15 Lập trình trên nền tảng Android  Khoa CNTT - Hutech Bước 7.3: bổ sung EditText và Button vào second layout như mô tả sau

Ngày đăng: 25/08/2016, 21:48

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan