Pages

Thứ Ba, 18 tháng 6, 2019

SimpleAdapter

Simple Adapter trong Android

SimpleAdapter thì đúng như chữ simple – tức đơn giản. Nó là một Adapter đơn giản và dễ hiểu để ánh xạ dữ liệu vào những View được định nghĩa trong một tập tin XML. Bạn có thể chỉ rõ dữ liệu sẽ được đóng gói trong một danh sách như là một ArrayList của việc ánh xạ. Mỗi phần tử trong ArrayList là một thể hiện của một dòng trên ListView. Công việc ánh xạ này nó chứa dữ liệu cho mỗi dòng. Bạn cũng có thể chỉ rõ một tập tin XML chứa nhiều điều khiển (widget) mà được dùng để thể hiện một dòng và ta sẽ ánh xạ từng giá trị trong từng phần tử trong ArrayList sang từng widget nằm trên từng dòng. Gắn dữ liệu vào các Views xảy ra trong 2 giao đoạn. Sẽ được trình bày trong các phần sau.

Cú pháp sử dụng SimpleAdapter

  SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)

Trong code trên cách sử dụng một SimpleAdapter. Sau đây là giải thích  tất cả các tham số được sử dụng SimpleAdapter để hiển thị một danh sách các phần tử trong một ListView hoặc GridView.

1. context: 

Tham số đầu tiên là context dùng để tham chiếu đến lớp hiện tại.Thông thường sử dụng từ khóa this. Ngoài ra, chúng ta cũng có thể sử dụng getApplicationContext(), getActivity() để thay thế từ khóa this.  getApplicationContext(), được sử dụng trong Activity, còn getActivity() được sử dụng trong Frament.

Ví dụ sau thiết lập lớp hiện tại trong Adapter

  SimpleAdapter(this, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)

2. data:

Tham số thứ 2 là data là một danh sách dữ liệu. Mỗi mục trong Danh sách tương ứng với một hàng trong danh sách. Maps dùng để chứa dữ liệu trên mỗi hàng.

Ví dụ sau chúng ta thiết lập map là một kiểu arrayList

  SimpleAdapter(this, hashmapData, int resource, String[] from, int[] to)

3. resource:

Tham số thứ 3 là tài nguyên (resource) id được sử dụng thiết lập các danh sách trong Layout. Trong Layout có thể TextView, ImageView, Button .v.v

Ví dụ sau chúng ta tạo một Layout có tên custom_list_items.xml

  <?xml version="1.0" encoding="utf-8"?>  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"      android:layout_width="match_parent"      android:layout_height="wrap_content">        <ImageView          android:id="@+id/imageView"          android:layout_width="50dp"          android:layout_height="50dp"          android:padding="5dp"          android:layout_alignParentRight="true"          android:layout_marginRight="10dp"          android:src="@drawable/ic_launcher" />        <TextView          android:id="@+id/textView"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:padding="@dimen/activity_horizontal_margin"          android:text="Demo"          android:textColor="#000" />  </RelativeLayout>  

Bây giờ, chúng ta truyền tham số thứ 3 cho SimpleAdapter

  SimpleAdapter (this, hashmapData, R.layout.custom_list_items, String[] from, int[] to) 

4. from:

Tham số thứ 4 là một mảng chuỗi dữ liệu, hoặc một danh sách các tên cột trong Maps để liên kết với ListView hoặc GirdView

Ví dụ sau thiết lập một mảng các mục dữ liệu danh sách

  String fromArray[]={"userName","userImage"};  SimpleAdapter (this, hashmapData, R.layout.custom_list_items, fromArray, int[] to)

5. to:

Tham số thứ 5 là một mảng số nguyên để lưu trữ các id của View. Nhãn của cột được truyền vào tham số "from"

Ví dụ sau thiết lập một mảng id số nguyên của view

  int to[]={R.id.textView,R.id.imageView};  SimpleAdapter (this, hashmapData, R.layout.custom_list_items, fromArray,to)

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à SimpleAdapterFile->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="hiepsiit.com.simpleadapter.MainActivity" >   <ListView          android:id="@+id/simpleListView"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:divider="#000"          android:dividerHeight="2dp"          android:listSelector="#600"/>      </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"?>  <RelativeLayout 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="50dp"  android:layout_height="50dp"  android:padding="5dp"  android:layout_alignParentRight="true"  android:layout_marginRight="10dp"  android:src="@drawable/ic_launcher" />    <TextView  android:id="@+id/textView"  android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:padding="@dimen/activity_horizontal_margin"  android:text="Demo"  android:textColor="#000" />  </RelativeLayout>

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 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 hiepsiit.com.simpleadapter;    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.SimpleAdapter;  import android.widget.Toast;    public class MainActivity extends Activity {  	 ListView simpleListView;  	 String[] animalName={"Lion","Tiger","Monkey","Dog","Cat","Elephant"};//animal names array  	 int[] animalImages={R.drawable.lion,R.drawable.tiger,R.drawable.monkey,R.drawable.dog,R.drawable.cat,R.drawable.elephant};//animal 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<animalName.length;i++)          {              HashMap<String,String> hashMap=new HashMap<String, String>();//create a hashmap to store the data in key value pair              hashMap.put("name",animalName[i]);              hashMap.put("image",animalImages[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          SimpleAdapter simpleAdapter=new SimpleAdapter(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(),animalName[i],Toast.LENGTH_LONG).show();//show the selected image in toast according to position              }  			          });      }	    }  

Download ví dụ

Ứng dụng này được phát triển bởi adt bundleandroid 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