Tùy biến (Custom) lại SimpleAdapter
Thông thường ở chế độ mặc định các item (hay các dòng) trong ListView chỉ hiển thị các dòng text. Để tùy biến các item của ListView trông đẹp hơn, lập trình viên có thể thêm các biểu tượng (icon), checkbox hoặc bất cứ cái gì vào item. Đơn giản chỉ là cung cấp dữ liệu cho adapter để tạo ra tập các đối tượng hiển thị (view objects) cho mỗi item.
Tùy biến SimpleAdapter
Ví dụ sau chúng ta có lớp CustomAdapter kế thừa lớp SimpleAdapter
public class CustomAdapter extends SimpleAdapter { public CustomAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) { super(context, data, resource, from, to); } @Override public View getView(int position, View convertView, ViewGroup parent) { return super.getView(position, convertView, parent); } @Override public int getCount() { return super.getCount(); } }
Trong ví dụ trên chúng ta ghi đè (override) các phương thức BaseAdapter thường được sử dụng trongListView, GridView, Spinner
1. getCount(): Phương thức này trả về số dòng của List
@Override public int getCount() { int count=arrayList.size(); //counts the total number of elements from the arrayList return count;//returns the total count to adapter }
2. getView(int i, View view, ViewGroup viewGroup): Phương thức này được gọi tự động các mục danh sách để sẵn sàng hiển thị. Trong phương thức chúng ta thiết lập layout cho danh sách các mục bằng cách sử dụng lớp LayoutInflater và sau đó thêm dữ liệu cho các view: ImageView, TextView .v.v.
@Override public View getView(int i, View view, ViewGroup viewGroup) { View view=super.getView(position, convertView, parent); ImageView imageView=(ImageView) view.findViewById(R.id.imageView); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(context, arrayList.get(position).get("name"), Toast.LENGTH_SHORT).show(); } }); return view; }
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 2 mảng, 1 mảng cho image, 1 mảng cho tên image. Tiếp theo, chúng ta thiết lâp sự kiện cho ListView khi người sử dụng chọ một dòng dữ liệu sẽ hiển tên của image ra màn hình thông qua đối tượng Toast. 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à CustomSimpleAdapter: 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.customsimpleadapter.MainActivity" > <ListView android:id="@+id/simpleListView" android:layout_width="match_parent" android:layout_height="wrap_content" android:divider="#000" android:dividerHeight="2dp" /> </RelativeLayout>
Bước 3: Tạo mới một Activity list_view_items.xml vào trong thư mục layout và thêm vào 2 widget ImageView, TextView sẽ được hiển thị từng dòng trong ListView
<?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="wrap_content" android:background="#fff"> <ImageView android:id="@+id/imageView" android:layout_width="60dp" android:layout_height="60dp" android:layout_marginLeft="10dp" android:padding="5dp" android:src="@drawable/ic_launcher" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:padding="@dimen/activity_horizontal_margin" android:text="Demo" android:textColor="#000" /> </LinearLayout>
Bước 4: Tạo mới một lớp CustomSimpleAdapter.java bên trong package và thêm code sau:
package com.example.customsimpleadapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.SimpleAdapter; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; public class CustomSimpleAdapter extends SimpleAdapter { LayoutInflater inflater; Context context; ArrayList<HashMap<String, String>> arrayList; public CustomSimpleAdapter(Context context, ArrayList<HashMap<String, String>> data, int resource, String[] from, int[] to) { super(context, data, resource, from, to); this.context = context; this.arrayList = data; inflater.from(context); } @Override public View getView(final int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); ImageView imageView = (ImageView) view.findViewById(R.id.imageView); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(context, arrayList.get(position).get("name"), Toast.LENGTH_SHORT).show(); } }); return view; } }
Bước 5: 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 2 mảng, 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 com.example.customsimpleadapter; import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends Activity { ListView simpleListView; String[] fruitsNames = {"Apple", "Banana", "Litchi", "Mango", "PineApple"};//fruit names array int[] fruitsImages = {R.drawable.apple, R.drawable.banana, R.drawable.litchi, R.drawable.mango, R.drawable.pineapple};//fruits images array @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); simpleListView = (ListView) findViewById(R.id.simpleListView); ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>(); for (int i = 0; i < fruitsNames.length; i++) { HashMap<String, String> hashMap = new HashMap<String, String>();//create a hashmap to store the data in key value pair hashMap.put("name", fruitsNames[i]); hashMap.put("image", fruitsImages[i] + ""); arrayList.add(hashMap);//add the hashmap into arrayList } String[] from = {"name", "image"};//string array int[] to = {R.id.textView, R.id.imageView};//int array of views id's CustomSimpleAdapter simpleAdapter = new CustomSimpleAdapter(this, arrayList, R.layout.list_view_items, from, to);//Create object and set the parameters for simpleAdapter simpleListView.setAdapter(simpleAdapter);//sets the adapter for listView //perform listView item click event simpleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Toast.makeText(getApplicationContext(), fruitsNames[i], Toast.LENGTH_LONG).show();//show the selected image in toast according to position } }); } }
Ứ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
Chọn một dòng trên ListView:
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