Thứ Tư, 23 tháng 12, 2015

Hướng dẫn tạo ListView trong Android

Listview là gì?

  • Trong Android khi chúng ta muốn hiển thị dữ liệu dạng danh sách thì một trong các cách đó là dùng Listview. Hôm nay mình sẽ hướng dẫn tạo ListView trong lập trình Android từ cơ bản đến việc custom thành các Listview Phức tạp.
  • Có nhiều cách tạo ListView khác nhau tùy theo bài toán của bạn về mặt thông tin hiển thị lên từng item của ListView sẽ là khác nhau.

Các cách tạo listview

Có nhiều cách để tạo listview nhưng có 2 cách để tạo ra listview thường dùng

1. Sử dụng ArrayAdapter tạo nhanh listview simple. Làm ví dụ như hình sau:

Tạo listview trong Android

Bước 1: Các bạn tạo một Project mới (cách tạo ứng dụng project android)

Bước 2: Trong file xml khởi tạo một listview đặt id là lvData như đoạn code sau
<linearlayout
android:layout_height="“match_parent”"
android:layout_width="“match_parent”"
android:orientation="“vertical”"
tools:context="“.MainActivity”"
xmlns:android="“http://schemas.android.com/apk/res/android”"
xmlns:tools="“http://schemas.android.com/tools”">
<textview android:background="“#ff53a695″"
android:gravity="“center”"
android:layout_height="“50dp”"
android:layout_width="“fill_parent”"
android:text="“DevProListViewSample”/"
android:textcolor="“#fff”"
android:textsize="“25sp”">
<listview
android:id="“@+id/lvData”"
android:layout_height="“fill_parent”"
android:layout_width="“fill_parent”">
</listview>
</textview>
</linearlayout>

Bước 3: Xử lý dữ liệu trong file java
package com.devprodemolistview;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.lang.reflect.Array;
public class MainActivity extends Activity {
ArrayAdapter<string> adapter;
ListView lvData;
String[] arrData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 1. Lấy đối tượng listview từ file xml bằng id
lvData = (ListView) findViewById(R.id.lvData);
// 2. Khởi tạo dữ liệu cho mảng được hiển thị
arrData = new String[]{Android01, Android02, DevPro, Android04};
// 3. Khởi tạo adapter
adapter = new ArrayAdapter<string>
(this, android.R.layout.simple_list_item_1, arrData);
// 4. Đưa adapter vào listview
lvData.setAdapter(adapter);
adapter.notifyDataSetChanged();   
}
}
Bước 4: Chạy ứng dụng và được kết quả như trên.

2. Sử dụng BaseAdapter tạo custom item trong Listview. Ví dụ tạo listview như trong hình sau:

Tạo listview trong Android
Bước 1: Tạo project mới.
Bước 2: Tạo đối tượng (Class) cần hiển thị trong listview

public class Person {
private int id;
private String name;
private String phone;
public Person() {
}
public Person(int id, String name, String phone) {
this.id = id;
this.name = name;
this.phone = phone;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
Bước 3: Tạo giao diện xml cho item của listview
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
   android:layout_width=”fill_parent”
   android:layout_height=”wrap_content”
   android:layout_margin=”10dp”
   android:background=”#fff”
   android:orientation=”horizontal”
   android:padding=”10dp”>
   <ImageView
       android:layout_width=”50dp”
       android:layout_height=”50dp”
       android:src=”@drawable/devpro” />
   <LinearLayout
       android:layout_width=”fill_parent”
       android:layout_height=”wrap_content”
       android:layout_marginLeft=”10dp”
       android:orientation=”vertical”>
       <TextView
           android:id=”@+id/txtName”
           android:layout_width=”fill_parent”
           android:layout_height=”25dp”
           android:gravity=”center_vertical”
           android:text=”Toan”
           android:textColor=”#000″
           android:textStyle=”bold” />
       <TextView
           android:id=”@+id/txtPhone”
           android:layout_width=”fill_parent”
           android:layout_height=”25dp”
           android:gravity=”center_vertical”
           android:text=”0123″ />
   </LinearLayout>
</LinearLayout>
Bước 4: Custom lại adapter
public class CustomAdapter extends BaseAdapter {
   ArrayList<Person> listData;
   LayoutInflater inflater; 
   // Hàm tạo của custom
   public CustomAdapter(Context context, ArrayList<Person> listData) {
       this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       this.listData = listData;
   }
   // Trả về số lượng phần tử được hiển thị trong listview
@Override
   public int getCount() {
       return listData.size();
   }
   // Trả về đối tượng được lấy theo vị trí
@Override
   public Object getItem(int position) {
       return listData.get(position);
   }
   @Override
   public long getItemId(int position) {
       return 0;
   }
   // Hàm quan trọng nhất, hiển thị giao diện của listview
@Override
   public View getView(int position, View convertView, ViewGroup parent) {
       // Lấy ra đối tượng cần hiển thị ở vị trí thứ position
Person item = listData.get(position);
       // Khai báo các component
TextView txtName, txtPhone;
       // Khởi tạo view.
if (convertView == null) {
           convertView = inflater.inflate(R.layout.person_item_layout, parent, false);
       }
       txtName = (TextView) convertView.findViewById(R.id.txtName);
       txtPhone = (TextView) convertView.findViewById(R.id.txtPhone);
       // Set dữ liệu vào item của list view
txtName.setText(item.getName());
       txtPhone.setText(item.getPhone());
       return convertView;
   }
}
Bước 5: Xử lí dữ liệu trong file java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 1. Lấy đối tượng listview từ file xml bằng id
lvData = (ListView) findViewById(R.id.lvData);
// 2. Khởi tạo dữ liệu cho mảng được hiển thị
creatData();
// 3. Khoi tao adapter
adapter = new CustomAdapter(this, listData);
// 4. setAdapter cho listview
lvData.setAdapter(adapter);
   adapter.notifyDataSetChanged();
}
// Khởi tạo danh sách dữ liệu cần hiển thị lên listview
private void creatData(){
listData = new ArrayList<>();
for (int i= 0; i< 10; i++){
listData.add(new Person(i, DevPro+i, 0123 456 78+i));
}
}

3. Bắt sự kiện cho listview


  • Bắt sự kiện click vào một item của listview

//sử dụng hàm setOnItemClickListener
lvData.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
       Person currentPersion = adapter.getItem(position);
       Toast.makeText(MainActivity.this,OnClick:  + currentPersion.getName(), Toast.LENGTH_SHORT).show();
   }
});

  • Bắt sự kiện nhấn và giữ vào một item của listview

//sử dụng hàm setOnItemLongClickListener
lvData.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
   @Override
   public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
       Person currentPersion = adapter.getItem(position);
       Toast.makeText(MainActivity.this,OnLongClick:  + currentPersion.getName(), Toast.LENGTH_SHORT).show();
       return false;
   }
});
Nguồn : Devpro

Bài Liên Quan

Hướng dẫn tạo ListView trong Android
4/ 5
Oleh
Được tạo bởi Blogger.