3. ListView
Có khả năng hiển thị 1 danh sách các item
Người dùng có thể cuộn lên/xuống để duyệt qua
các item này
ListView nhận dữ liệu truyền vào từ Adapter
Adapter quy định mỗi row trong list hiển thị như
thế nào
Adapter được gán qua phương thức setAdapter
của listview obj, hoặc setListAdapter ở
ListActivity
hoccungdoanhnghiep.com
4. Basic ListView
Khởi tạo 1 layout để mô tả content của 1 row
trong list view muốn hiển thị:
/res/layout/listnotes_item.xml
Activity hiển thị listview sẽ được extends từ
class ListActivity
Để kết nối từ listview - layout - nội dung hiển thị,
sẽ cần lớp Adapter:
Khởi tạo array các string muốn đưa vào list:
String[]
new ArrayAdapter<String>(this, layout, String[]);
gán vào listview: setListAdapter
hoccungdoanhnghiep.com
5. Các loại Adapter cho ListView
BaseAdapter: lớp common chứa các phương
thức để gán data cho ListView hoặc spinner
ArrayAdapter: Thường dụng để xử lý các loại
content dạng Array hoặc List
SimpleCursorAdapter: chuyên sử dụng để handle
các loại data liên quan đến cursor lấy được từ
sqlite db
hoccungdoanhnghiep.com
6. Custom Adapter
Để tùy biến các adapter theo ý muốn, ta thừa kế lớp
tương ứng. Ở trong ví dụ này: public class
NoteCursorAdapter extends SimpleCursorAdapter
Khởi tạo layout dành riêng cho item trong list: /res/layout/
note_item.xml
Trong class NoteCursorAdapter:
Khai báo constructor: public NoteCursorAdapter(Context
context, Cursor cursor, String[] from, int[] to)
Khai báo nested static class ItemViewHolder chứa các thành
phần của 1 item trong list. Class này sẽ giữ lại các thành
phần của layout khi bind data tương ứng vào
Override hàm: public View getView(int position, View
convertView, ViewGroup parent)
Trong hàm này, set up các thành phần tương ứng cho item trong list
để hiển thị
hoccungdoanhnghiep.com
7. Các thành phần có thể tùy biến nhờ custom Adapter
Layout cho mỗi item bên trong list view
Event tương ứng với các subview của layout-
item
hoccungdoanhnghiep.com
8. Xử lý sự kiện cho ListView
ListView thường được bắt sự kiện
setOnItemClickListener để handle mỗi khi người
dùng click vào row trong list
Để bắt được sự kiện này, trong layout của item,
các subview mà có khả năng focusable phải set
thành false:
android:focusable="false"
android:focusableInTouchMode="false"
Các subview gồm: ImageView, ImageButton,
Button,…
hoccungdoanhnghiep.com