ListView trong Android
Android ListView là một view chứa nhóm các mục và hiển thị trong một danh sách có thể cuộn được. Người sử dụng có thể chọ mục trong danh sách bằng cách Click.
ListView code trong XML:
<ListView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/simpleListView" android:layout_width="match_parent" android:layout_height="wrap_content" tools:context="abhiandroid.com.listexample.MainActivity"> </ListView>
Giao diện ListView lúc thiết kế
Thuộc tính thường dùng của ListView
Bây giờ chúng xem một số thuộc tính hay sử dụng trong ListView trong tập tin XML
1. android:id: Là thuộc tính duy nhất của ListView. Xem ví dụ sau:
<!-- Id of a list view uniquely identify it--> <ListView android:id="@+id/simpleListView" android:layout_width="fill_parent" android:layout_height="wrap_content" />
Dựa vào Id ta sẽ lấy được control theo đúng Id này, xem code bên dưới để biết cách lấy control theo Id:
ListView simpleList = (ListView) findViewById(R.id.simpleListView);
2. android:divider: Thuộc tính này có thể là một image hay màu dùng để phân chia giữa các dòng trong ListView. Ví dụ sau chúng ta dùng màu đỏ để phân chia giữa các dòng trong ListView
<!--Divider code in ListView--> <ListView android:id="@+id/simpleListView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:divider="#f00" android:dividerHeight="1dp" />
3. android:dividerHeight: Thuộc tính này xác định chiều cao của thuộc tính android:divider. Trong ví dụ trên chúng ta xác định chiều cao ListView là 1dp
4. android:listSelector: Thuộc tính này thường được s
ử dụng để thiết lập màu hoặc hình dòng được chọn trong listView. Thường nó sử dụng màu cam hoặc màu xanh dương, nhưng chúng ta cũng có thể thiết lập lại màu hoặc image cho ListView. Ví dụ chúng ta thiết lập màu xanh lá cây khi người sử dụng chọn 1 dòng dữ liệu trong ListView.
<!-- List Selector Code in ListView --> <ListView android:id="@+id/simpleListView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:divider="#f00" android:dividerHeight="1dp" android:listSelector="#0f0"/> <!--list selector in green color-->
Sự kiện thường dùng trong ListView
1. setOnItemClickListener: Sự kiện này xảy ra khi người dùng click lên ListView. Xem ví dụ sau:
lv.setOnItemClickListener(new AdapterView .OnItemClickListener() { public void onItemClick( AdapterView<?> arg0,View arg1, int arg2,long arg3) { txtchon.setText("position : "+ arg2+ "; value ="+arrList.get(arg2)); } });
Trong hàm onItemClick các bạn thấy có tham số thứ 3 arg2 là vị trí cùa ListView, tham số thứ 4 arg3 là id của mỗi dòng của ListView
2. setOnItemLongClickListener: Sự kiện được gắn cho ListView Item, khi nhấn lâu từ 2.5 tới 3 giây thì sự kiện này sẽ sảy ra. Xem ví dụ sau:
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { arrList.remove(arg2);//xóa phần tử thứ arg2 adapter.notifyDataSetChanged(); return false; } });
Trong hàm onItemClick các bạn thấy có tham số thứ 3 arg2 là vị trí cùa ListView, tham số thứ 4 arg3 là id của mỗi dòng của ListView
Adapter sử dụng trong Android
Một Adapter là một đối tượng của một lớp cài đặt giao diện Adapter
. Nó đóng vai trò như là một liên kết giữa một tập hợp dữ liệu và một Adapter View, một đối tượng của một lớp thừa kế lớp trừu tượng AdapterView
. Tập hợp dữ liệu có thể là bất cứ điều gì mà trình bày dữ liệu một cách có cấu trúc. Mảng, các đối tượng List
và các đối tượng Cursor
thường sử dụng bộ dữ liệu.
Có 2 loại Adapter :
- Array Adapter
- Base Adapter
Một ListAdapter có thể quản lí một ListView chứa danh sách các phần tử có kiểu bất kì. Việc rất đơn giản, bạn chỉ cần “móc nối” dữ liệu với TextView thông qua ID của nó với mỗi dòng trong ListView là một TextView – ví dụ như ListView gồm danh sách tên sinh viên mà thôi. Nếu bạn muốn mỗi dòng ListView phức tạp hơn tức là gồm nhiều thành phần hơn thì nên dùng một mảng để giữ tất cả các ID của các TextView trong. Từng cách làm sẽ được nói trong các phần sau:
ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.ListView,R.id.textView,StringArray);
Ví dụ: Trong ví dụ này chúng ta sẽ làm ứng dụng gồm có một ListView. Trước tiên, chúng ta tạo 1 mảng dữ liệu, sau đó kiết nối với ListView thông qua đối tượng ArrayAdapter. Tiến hành tạo project, vào thư mục res /layout -> activity_main.xml thiết kế giao diện sau:
Bước 1: Tạo một project tên là ListView: File->New->Android Application Project điền các thông tin ->Next ->Finish
Bước 2: Mở res -> layout -> xml (hoặc) activity_main.xml và thêm code trong Relaytive Layout.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.listview.MainActivity" > <ListView android:id="@+id/simpleListView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:divider="@color/material_blue_grey_800" android:dividerHeight="1dp" /> </RelativeLayout>
Bước 3: Tạo mới một Activity activity_listview.xml vào trong thư mục layout và thêm vào 1 widget TextView.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/textView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:padding="@dimen/activity_horizontal_margin" android:textColor="#000" /> </LinearLayout>
Bước 3: Mở src -> package -> MainActivity.java
Trong bước này chúng ta khởi tạo ListView. Tiếp theo, chúng ta tạo 1 mảng dữ liệu và kết nối ListView thông qua đối tượng ArrayAdapter.
package com.example.listview; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends Activity { ListView simpleList; String countryList[] = {"India", "China", "australia", "Portugle", "America", "NewZealand"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); simpleList = (ListView)findViewById(R.id.simpleListView); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.activity_listview, R.id.textView, countryList); simpleList.setAdapter(arrayAdapter); } }
Ứng dụng này được phát triển bởi adt bundle, android 4.2 sử dụng minimum sdk 11 and target sdk 21.
Kết quả khi chạy ứng dụng
2. Base Adapter: Là lớp adpater cơ sở cho các Adapter thường dùng khác như ArrayAdapter<T>, CursorAdapter, SimpleAdapter. BaseAdapter thường đóng vai trò Adapter cho các ListView và Spinner
Ví dụ: Trong ví dụ này chúng ta sẽ làm ứng dụng gồm có một ListView để hiển thị tên các nước cùng với lá cờ nước đó. Tiến hành tạo project, vào thư mục res /layout -> activity_main.xml thiết kế giao diện sau:
Bước 1: Tạo một project tên là ListViewBaseAdapter: File->New->Android Application Project điền các thông tin ->Next ->Finish
Bước 2: Mở res -> layout -> xml (hoặc) activity_main.xml và thêm code trong Linear Layout.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ListView android:id="@+id/simpleListView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:divider="@color/material_blue_grey_800" android:dividerHeight="1dp" android:footerDividersEnabled="false" /> </LinearLayout>
Bước 3: Tạo mới một Activity activity_listview.xml vào trong thư mục layout và thêm code sau:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <ImageView android:id="@+id/icon" android:layout_width="50dp" android:layout_height="50dp" android:src="@drawable/ic_launcher" /> <TextView android:id="@+id/textView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:padding="@dimen/activity_horizontal_margin" android:textColor="#000" /> </LinearLayout>
Bước 4: Tạo mới một lớp CustomAdapter.java bên trong package và thêm code sau:
package hiepsiit.com.listviewbaseadapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; public class CustomBaseAdapter extends BaseAdapter{ Context context; String countryList[]; int flags[]; LayoutInflater inflter; public CustomBaseAdapter(Context context, String[] countryList, int[] flags) { super(); this.context = context; this.countryList = countryList; this.flags = flags; inflter = (LayoutInflater.from(context)); } @Override public int getCount() { // TODO Auto-generated method stub return countryList.length; } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub convertView = inflter.inflate(R.layout.activity_listview, null); TextView country = (TextView) convertView.findViewById(R.id.textView); ImageView icon = (ImageView) convertView.findViewById(R.id.icon); country.setText(countryList[position]); icon.setImageResource(flags[position]); return convertView; } }
Bước 5: Open src -> package -> MainActivity.java
Trong bước này chúng ta khởi tạo ListView. Tiếp theo, chúng ta tạo 1 mảng cho image, 1 mảng cho tên image. Lưu các hình ảnh vào thư mục drawable.
package hiepsiit.com.listviewbaseadapter; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.ListView; public class MainActivity extends Activity { ListView simpleList; String countryList[] = {"India", "China", "australia", "Portugle", "America", "NewZealand"}; int flags[] = {R.drawable.india, R.drawable.china, R.drawable.australia, R.drawable.portugle, R.drawable.america, R.drawable.new_zealand}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); simpleList = (ListView)findViewById(R.id.simpleListView); CustomBaseAdapter adapter = new CustomBaseAdapter(this, countryList, flags); simpleList.setAdapter(adapter); } }
Ứng dụng này được phát triển bởi adt bundle, android 4.2 sử dụng minimum sdk 11 and target sdk 21.
Kết quả khi chạy ứng dụng:
Cập nhật công nghệ từ Youtube tại link: https://www.youtube.com/channel/UCOxeYcvZPGf-mGLYSl_1LuA/videos
Để tham gia khóa học công nghệ truy cập link: http://thuvien.hocviendaotao.com
Mọi hỗ trợ về công nghệ email: dinhanhtuan68@gmail.com