[Học lập trình Android] Tạo Listview bằng ArrayAdapter

ngày 24-08-2017

Bài tập được trích từ chương trình Lập trình viên Android tại Trung tâm Tin học Khoa học Tự nhiên.
 
Mục tiêu:
Hiển thị dữ liệu theo dạng danh sách trên ListView với sự hỗ trợ của ArrayAdapter
Tuỳ biến giao diện cho ListView với layout tự tạo
Yêu cầu:
Có kiến thức Project bằng AndroidStudio
Có kiến thức về các view cơ bản và layout linear, relative
Có kiến thức Class, ArrayList
 
Tạo Listview bằng ArrayAdapter
 
Hướng dẫn :
Mô tả ứng dụng:
- Hiển thị danh sách các quốc gia với các thông tin như tên quốc gia, cờ của quốc gia, dân số
- Khi người dùng chọ vào một quốc gia trên Activity ứng dụng sẽ hiện thông báo dạng Toast về chi tiết của quốc gia đó
Hướng dẫn thực hiện: 
 

Bước 1: Xây dựng Project với AndroidStudio

 

Bước 2: 

 

Bước 2.1: Xây dựng giao diện:

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_list_view_multi_data"
    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"
    android:orientation="vertical"
    tools:context="com.example.vudinhai.bt_listview_gridview_spinner_auto.ListViewMultiDataActivity">
<!--tạo control listview-->
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView" />
</LinearLayout>

 

Bước 2.2: Xây dựng giao diện cho từng dòng để hiển thị trên ListView

 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/img"
        android:src="@drawable/aruba"/>
 
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginLeft="5dp"
        android:orientation="vertical">
        <TextView
            android:text="TextView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:gravity="left|center_vertical"
            android:textSize="24dp"
            android:id="@+id/textView" />
 
        <TextView
            android:text="TextView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:gravity="top|center_vertical"
            android:textSize="14dp"
            android:id="@+id/textView2" />
    </LinearLayout>
 
</LinearLayout>

 

Bước 3: Xây dựng class Coutry

 

public class Country {
    String name;
    String populate;
    int img;
 
    public Country() {
    }
 
    public Country(String name, String populate) {
        this.name = name;
        this.populate = populate;
    }
 
    public Country(String name, String populate, int img) {
        this.name = name;
        this.populate = populate;
        this.img = img;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getPopulate() {
        return populate;
    }
 
    public void setPopulate(String populate) {
        this.populate = populate;
    }
 
 
    public int getImg() {
        return img;
    }
 
    public void setImg(int img) {
        this.img = img;
    }
 
    @Override
    public String toString() {
        return "Country{" +
                "name='" + name + '\'' +
                ", populate='" + populate + '\'' +
                ", img=" + img +
                '}';
    }
}

 

Bước 4: Xây dựng lớp CustomArrayAdapter kế thừa từ ArrayAdapter để hiển thị dữ liệu lên listView

 

public class CustomArrayAdapter extends ArrayAdapter<Country> {
 
    Context context;
    ArrayList<Country> arrayList;
    int layoutResource;
//Hàm khởi tạo cho CustomArrayAdapter
    public CustomArrayAdapter(Context context, int resource, ArrayList<Country> objects) {
        super(context, resource, objects);
        this.context = context;
        this.arrayList = objects;
        this.layoutResource = resource;
    }
 
    @NonNull
    @Override
//Hàm khởi tạo cho các dòng để hiển thị trên ListView
    public View getView(int position, View convertView, ViewGroup parent) {
 
        LayoutInflater inflater = LayoutInflater.from(context);
        convertView = inflater.inflate(layoutResource,null);
//Hàm khởi thêm dữ lieu vào các View từ arrayList thông qua position
        TextView txt1 = (TextView)convertView.findViewById(R.id.textView);
        txt1.setText(arrayList.get(position).getName());
 
        TextView txt2 = (TextView)convertView.findViewById(R.id.textView2);
        txt2.setText(arrayList.get(position).getPopulate());
 
        ImageView img = (ImageView)convertView.findViewById(R.id.img);
        img.setImageResource(arrayList.get(position).getImg());
 
        return convertView;
    }
}

 

Bước 5: Viết code cho MainActivity

 

public class ListViewMultiDataActivity extends AppCompatActivity {
//khai báo cac view
    ListView listView;
    ArrayList<Country> arrayList;
    CustomArrayAdapter customArrayAdapter;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_view_multi_data);
//map listview xml sang java
        listView = (ListView)findViewById(R.id.listView);
//khởi tạo dữ liệu mẫu 
        arrayList = new ArrayList<>();
        arrayList.add(new Country("Albani", "1000000",R.drawable.aruba));
        arrayList.add(new Country("Brazil", "9000000",R.drawable.australia));
        arrayList.add(new Country("United State", "2000000",R.drawable.canada));
        arrayList.add(new Country("Viet Nam", "3000000", R.drawable.czech_republic));
        arrayList.add(new Country("Japan", "4000000",R.drawable.china));
        arrayList.add(new Country("Russia", "4000000", R.drawable.denmark));
//khởi tạo customArrayAdapter
        customArrayAdapter = new CustomArrayAdapter(ListViewMultiDataActivity.this,
              R.layout.layout_row_item,arrayList);
        listView.setAdapter(customArrayAdapter);
//Tương tác với ListView
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(ListViewMultiDataActivity.this, arrayList.get(position).toString() , Toast.LENGTH_SHORT).show();
            }
        });
    }
}

 

Bước 6: Chạy và kiểm tra kết quả

 

Tạo Listview bằng ArrayAdapter Tạo Listview bằng ArrayAdapter

Chúc các bạn học tốt!

Trung tâm Tin học ĐH Khoa học Tự nhiên