ListView trong Android

LISTVIEW TRONG ANDROID

Khi lập trình Android, với một ứng dụng đơn giản, thì chắc hẳn làm gì đi nữa thì phải “đụng” tới ListView. ListView là một dạng hiển thị dữ liệu rất rất phổ biến trên các thiết bị Android. Ta thường gặp các ListView dưới các dạng danh sách, trong danh sách đó chứa những dòng dữ liệu (item) tương tự nhau về mặt cấu trúc. Và bài viết này, chúng tôi sẽ giới thiệu với các bạn cách tạo một ListView trong lập trình Android.

may-tinh-android-0

Đến với ListView, việc đầu tiên của một người lập trình là phải xác định được một dòng dữ liệu (item) mà ta sắp tạo chứa những gì (TextView, ImageView, Button, EditText,…) và thiết kế chúng trong một layout riêng. Thứ hai, ta cần tạo một lớp đối tượng để quản lý các Control tương ứng trong layout đó. Xác định, thiết kế giao diện 1 item, ta tiến hành xây dựng Adapter, đây là bước trung gian mà Android hỗ trợ để ta có thể đổ dữ liệu từ các item sang dạng list trong ListView. Trong Adapter đó, ta cần làm những gì, thì đến mời các bạn theo dõi phần tiếp theo của bài viết.

Mục lục bài viết:

1. Thiết kế, xác định một dòng dữ liệu trong ListView

2. Xây dựng AdapterListView

3. Đổ adapter vào ListView

4. Video xây dựng ListView trên Android

listview-in-android-0

Ví dụ về ListView trong Android

1. Thiết kế, xác định một dòng dữ liệu trong ListView

Ví dụ, ta sẽ xây dựng ứng dụng như hình bên trên. Nguồn hình các lá cờ các bạn có thể tải tại: https://goo.gl/Ot8Uwv . Sau khi tải về, giải nén và các bạn copy tất cả tấm hình đó, vào Android Studio, ngay thư mục drawable vào Paste (Ctrl+V) vào thẳng trong đó.

Theo hình trên, ta dễ nhận thấy một dòng dữ liệu bao gồm: một ImageViewhai TextView (tên nước, tên thủ đô). Rất dễ để ta ta xây dựng một Layout như vậy. Nhấn phải chuột và thư mục layout, chọn New, chọn Layout Resource file. Đặt tên là item_listview.xml (tên tự đặt) và chọn kiểu layout là Relative Layout. Ta sẽ thiết kế giao diện như sau:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="100dp"
        app:srcCompat="@drawable/australia"
        android:id="@+id/imgCo"
        android:layout_height="100dp" />

    <TextView
        android:text="TenNuoc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtTenNuoc"
        android:textSize="30dp"
        android:textStyle="bold"
        android:textColor="#000000"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="10dp"
        android:layout_toRightOf="@+id/imgCo"
        android:layout_toEndOf="@+id/imgCo" />

    <TextView
        android:text="ThuDo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtThuDo"
        android:textStyle="italic"
        android:textColor="#000000"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="20dp"
        android:layout_below="@+id/txtTenNuoc"
        android:layout_toRightOf="@+id/imgCo"
        android:layout_toEndOf="@+id/imgCo" />

</RelativeLayout>

Sau khi thiết kế, giao diện một dòng dữ liệu tạm thời của ta sẽ là:

listview-in-android-1

Một dòng dữ liệu ListView

Việc tiếp theo trong bước 1, là ta sẽ tạo một lớp đối tượng đơn giản để quản lý item này. Trường hợp này, ta sẽ tạo một lớp Country với cấu trúc gồm: tennuoc, thudo (kiểu String) và idhinh (kiểu Integer). Để tạo một tập tin java mới, trong thư mục java chọn tiếp thư mục mà ta code chính (thư mục chứa MainActivity.java), chuột phải chọn New, Java Class đặt tên là Country. Ta tiến hành code như sau:

listview-in-android-2

Thêm Country vào thư mục chứa MainActivity

package com.example.baobao.examplelistview;

/**
 * Created by BaoBao on 11/10/2016.
 */

public class Country {
    private String tennuoc;
    private String thudo;
    private Integer idhinh;

    public Country(String tennuoc, String thudo, Integer idhinh) {
        this.tennuoc = tennuoc;
        this.thudo = thudo;
        this.idhinh = idhinh;
    }

    public String getTennuoc() {
        return tennuoc;
    }

    public void setTennuoc(String tennuoc) {
        this.tennuoc = tennuoc;
    }

    public String getThudo() {
        return thudo;
    }

    public void setThudo(String thudo) {
        this.thudo = thudo;
    }

    public Integer getIdhinh() {
        return idhinh;
    }

    public void setIdhinh(Integer idhinh) {
        this.idhinh = idhinh;
    }
}

2. Xây dựng AdapterListView

Như đã trình bày, ta sẽ tạo một lớp AdapterListView, làm bước trung gian để đổ dữ liệu sang ListView, các công đoạn tạo một ApdaterListView như sau. Tạo một lớp có tên AdapterListView nằm trong thư mục chứa MainActivity.java. Lớp AdapterListView này kế thừa từ BaseAdapterListAdapter như sau:

public class AdapterListView extends BaseAdapter implements ListAdapter{
    private Context context;
    private Country[] data;

    public AdapterListView(Context context, Country[] data) {
        this.context = context;
        this.data = data;
    }
}

Trong đó, biến context, data là hai biến mà ta cần để lấy dữ liệu từ bên ngoài để xử lý. Lúc này, Android Studio báo lỗi đỏ chỗ này. Các bạn nhấn chuột vào dòng này và nhấn Alt+Enter chọn Implemets methods. Ta tiến hành import tất cả các hàm override trong đó.

listview-in-android-3

Chọn tất cả các hàm này và nhấn Ok

Ta tiến hành code theo mẫu sau để tiến hành tạo một AdapterListView:

package com.example.baobao.examplelistview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;

/**
 * Created by BaoBao on 11/10/2016.
 */

public class AdapterListView extends BaseAdapter implements ListAdapter{
    private Context context;
    private Country[] data;

    public AdapterListView(Context context, Country[] data) {
        this.context = context;
        this.data = data;
    }

    @Override
    public int getCount() {
        return data.length;
    }

    @Override
    public Object getItem(int position) {
        return data[position];
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        convertView = LayoutInflater.from(context).inflate(R.layout.item_listview,null);
        TextView txtTenNuoc = (TextView)convertView.findViewById(R.id.txtTenNuoc);
        TextView txtThuDo = (TextView)convertView.findViewById(R.id.txtThuDo);
        ImageView imgCo = (ImageView)convertView.findViewById(R.id.imgCo);
        txtTenNuoc.setText(data[position].getTennuoc());
        txtThuDo.setText(data[position].getThudo());
        imgCo.setImageResource(data[position].getIdhinh());
        return convertView;
    }
}

Trong đó, hàm mà ta cần chú ý là hàm getView, đây là hàm trả về một View (hay một giao diện Item mà ta đã thiết kế). Trong hàm này, ta cần gán layout cho convertView từ contextitem_listview.xml như trên. Các dòng tiếp theo là tiến hành ánh xạ cũng như gán giá trị cho từng Control dựa vào Country thứ position trong mảng data.

3. Đổ Adapter và ListView

Đã có AdapterListView thì việc cuối cùng ta chỉ cần qua MainActivity.java gọi hàm set Adapter cho ListView là hoàn thành ứng dụng. Tuy nhiên, ta cần phải khởi tạo một mảng Country. Mảng Country này chứa thông tin của một Country (Tên nước, tên thủ đô, quốc kỳ tương ứng). Ta sẽ dễ dàng tạo mảng Country đó như sau, tại MainActivity.java, ở ngoài hàm onCreate:

private void createArrayCountry() {
        String[] arrayTenNuoc = new String[]{"Australia","Brazil","Britain","Canada","France","Germany","Japan","Korea","USA","VietNam"};
        String[] arrayThuDo = new String[]{"Canberra","Brasilia","London","Ottawa","Paris","Berlin","Tokyo","Seoul","New York","Hà Nội"};
        arrayCountry = new Country[arrayTenNuoc.length];
        Integer[] arrayIdFlag = new Integer[]{R.drawable.australia,R.drawable.brazil,R.drawable.britain,R.drawable.canada,R.drawable.france,R.drawable.germany,R.drawable.japan,R.drawable.korea,R.drawable.usa,R.drawable.vietnam};
        for(int i = 0;i<arrayTenNuoc.length;i++)
        {
            Country country = new Country(arrayTenNuoc[i],arrayThuDo[i],arrayIdFlag[i]);
            arrayCountry[i] = country;
        }
    }

Lúc này, ta sẽ khởi tạo ba biến cục bộ bên ngoài hàm onCreate gồm:

ListAdapter adapter;
ListView listView;
Country[] arrayCountry;

Việc cuối cùng là ánh xạ ListView và setAdapterListView, ở hàm onStart:

@Override
protected void onStart() {
    super.onStart();
    listView = (ListView)findViewById(R.id.listView);
    createArrayCountry();
    adapter = new AdapterListView(getApplicationContext(),arrayCountry);
    listView.setAdapter(adapter);
}

Việc cuối cùng, ta chỉ cần chạy máy ảo thì ta sẽ được một ListView như hình bên trên.

4. Xây dựng ListView trên Android

Cảm ơn các bạn đã theo dõi bài viết !