Custom ListView trong Android

Mời các bạn đến với bài hướng dẫn Custom ListView trong Android. Sau khi đã tìm hiểu về ListView trong Android, với item mặc định trong ListView khá đơn điệu và không bắt mắt để giải quyết vấn đề này ta sử dụng Custom ListView trong Android.

Custom ListView trong Android

Bây giờ tôi cùng các bạn sẽ cùng nhau tìm hiểu về Custom ListView trong Android. Vậy là thế nào để Custom ListView.

1. Custom ListView trong Android là gì?

Custom ListView là thực hiện thiết kế các item cho ListView chứ không sử dụng các item mặc định mà Android cung cấp. Mục đích thiết kế item cho ListView là để giao diện ListView thêm sống động và đẹp mắt.

Về phần khái niệm ListView trong Android mình đã trình bày ở bài trước bạn nào chưa đọc thì có thể xem qua. Sau khi đã tìm hiểu khái niệm Custom ListView chúng ta sẽ đi cụ thể hơn với ví dụ sử dụng Custom ListView trong Android.

2. Ví dụ sử dụng Custom ListView trong Android

Đến với ví dụ sử dụng custom ListView trong Android tôi có một danh sách các ngôn ngữ lập trình cần hiển thị lên ListView. Tương ứng với mỗi ngôn ngữ là một item trong ListView với Item này tôi không sử dụng item mặc định mà Android cung cấp mà tự thiết kế item theo ý muốn. Và đây là source code ví dụ Custom ListView trong Android.

Sau đây là 5 bước chuẩn để thực hiện quá trình tạo Project sử dụng ListView trong Android.

Bước 1: Khởi tạo project với tên CustomListViewExample.

Chọn File >> New >> New Project. Xuất hiện form và đặt tên project CustomListViewExample sau đó click Finish.

Cấu trúc project CustomListViewExample như sau.

Custom ListView trong Android

Bước 2: Vào res >> layout >> custom_list_view_activity.xml và thêm vào đoạn code dưới đây. Trong ví dụ sử dụng custom ListView tôi sẽ lấy danh sách ngôn ngữ lập trình đổ vào trong ListView.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    tools:context="com.teamvietdev.customlistviewexample.activity.CustomListViewExampleActivity">

    <ListView
        android:id="@+id/idListView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

Và đây là nội dụng item mà tôi đã custom: res >> layout >> item_custom_list_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:id="@+id/idLinearLayout"
    android:layout_height="80dp"
    android:layout_marginTop="1dp"
    android:background="#FFFFFF"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="120dp"
        android:layout_height="match_parent"
        android:layout_weight="1.0"
        android:gravity="center"
        android:orientation="vertical"
        android:weightSum="1">
        <ImageView
            android:id="@+id/logo"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:contentDescription="@null"
            android:gravity="center"
            android:src="@drawable/icon_java"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1.0"
        android:orientation="vertical"
        android:weightSum="1">
        <TextView
            android:id="@+id/tvLanguageName"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="left|center"
            android:text="ITEM EXAMPLE"
            android:textSize="20dp"
            android:textStyle="bold"/>
    </LinearLayout>

</LinearLayout>

Bước 3: vào package com.teamvietdev.customlistviewexample >> model

Tạo Language.java và thêm đoạn code sau đây vào.

package com.teamvietdev.customlistviewexample.model;

public class Language {
    private int id;
    private String name;

    public Language(int id, String name) {
        this.id = id;
        this.name = name;
    }

    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;
    }
}

vào package com.teamvietdev.customlistviewexample >> adapter

Tạo LanguageAdapter.java và thêm đoạn code sau đây vào.

package com.teamvietdev.customlistviewexample.adapter;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.teamvietdev.customlistviewexample.R;
import com.teamvietdev.customlistviewexample.model.Language;

import java.util.List;

public class LanguageAdapter extends BaseAdapter {
    private Context context;
    private int idLayout;
    private List<Language> listLanguage;
    private int positionSelect = -1;

    public LanguageAdapter(Context context, int idLayout, List<Language> listLanguage) {
        this.context = context;
        this.idLayout = idLayout;
        this.listLanguage = listLanguage;
    }

    @Override
    public int getCount() {
        if (listLanguage.size() != 0 && !listLanguage.isEmpty()) {
            return listLanguage.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

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

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(idLayout, parent, false);
        }

        TextView tvLanguageName = (TextView) convertView.findViewById(R.id.tvLanguageName);
        ImageView imageView = (ImageView) convertView.findViewById(R.id.logo);
        final LinearLayout linearLayout = (LinearLayout) convertView.findViewById(R.id.idLinearLayout);
        final Language language = listLanguage.get(position);

        if (listLanguage != null && !listLanguage.isEmpty()) {
            tvLanguageName.setText(language.getName());
           int idLanguage = language.getId();
            switch (idLanguage) {
                case 1:
                    imageView.setImageResource(R.drawable.icon_java);
                    break;
                case 2:
                    imageView.setImageResource(R.drawable.icon_android);
                    break;
                case 3:
                    imageView.setImageResource(R.drawable.icon_javafx);
                    break;
                case 4:
                    imageView.setImageResource(R.drawable.icon_web);
                    break;
                case 5:
                    imageView.setImageResource(R.drawable.icon_ruby);
                    break;
                case 6:
                    imageView.setImageResource(R.drawable.icon_c);
                    break;
                case 7:
                    imageView.setImageResource(R.drawable.icon_php);
                    break;
                case 8:
                    imageView.setImageResource(R.drawable.icon_wordpress);
                    break;
                default:
                    break;
            }
        }
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, language.getName(), Toast.LENGTH_LONG).show();
                positionSelect = position;
                notifyDataSetChanged();
            }
        });

        if (positionSelect == position) {
            linearLayout.setBackgroundColor(Color.BLUE);
        } else {
            linearLayout.setBackgroundColor(Color.WHITE);
        }
        return convertView;
    }

}

vào package com.teamvietdev.customlistviewexample >> activity

Tạo CustomListViewExampleActivity.java và thêm đoạn code sau đây vào.

package com.teamvietdev.customlistviewexample.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import com.teamvietdev.customlistviewexample.R;
import com.teamvietdev.customlistviewexample.adapter.LanguageAdapter;
import com.teamvietdev.customlistviewexample.model.Language;
import java.util.ArrayList;
import java.util.List;

public class CustomListViewExampleActivity extends AppCompatActivity {
    private List<Language> listLanguage;
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_list_view_activity);

        listView = (ListView) findViewById(R.id.idListView);
        listLanguage = new ArrayList<>();
        listLanguage.add(new Language(1, "Lập Trình Java"));
        listLanguage.add(new Language(2, "Lập Trình Android"));
        listLanguage.add(new Language(3, "Lập Trình JavaFX"));
        listLanguage.add(new Language(4, "Lập Trình Web"));
        listLanguage.add(new Language(5, "Lập Trình Ruby"));
        listLanguage.add(new Language(6, "Lập Trình C++"));
        listLanguage.add(new Language(7, "Lập Trình PHP"));
        listLanguage.add(new Language(8, "Lập Trình WordPress"));

        LanguageAdapter adapter = new LanguageAdapter(this, R.layout.item_custom_list_view, listLanguage);
        listView.setAdapter(adapter);

    }
}

Bước 4: Mở file AndroidManifest.xml và dán đoạn code sau đây vào.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.teamvietdev.customlistviewexample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/teamvietdev"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".activity.CustomListViewExampleActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Kết quả chạy ví dụ sử dụng Custom ListView trong Android như sau.

Custom ListView trong Android

Lời kết: Như vậy là các bạn đã thực hiện Custom ListView trong Android. Ngoài ra các bạn có thể theo dõi thêm các chuyên mục khác tại Team Việt Dev.

(Tác giả: Team Việt Dev)

Bình luận