[Android căn bản] Bài 7: Listview trong Android.

[Android căn bản] Bài 7: Listview trong Android.

Giới thiệu

Chào các bạn chúng ta lại gặp nhau trong Series Android truyền kì rồi. Hôm nay mình xin giới thiệu với các bạn một component của Android đó chính là Listview. Cái này chắc bạn cũng thấy thường xuyên rồi ví dụ như danh sach bài hát trong phần mềm nghe nhạc trong máy bạn chẳng hạn bạn thấy các bài hát có trong máy bạn sẽ được hiển thị thành 1 danh sách từ trên xuông dưới đúng không nào và bạn có thể vuốt để chọn các bài hát từ danh sách ấy.

Trong Android để hiển thị danh sách như vậy ta có thể sử dụng đến ListView, và trong Android sẽ có hai cách sử dụng Listview là sử dụng Listview mặc định và custom Listview.

Sử dụng ListView mặc định.

Với cách này chúng ta sẽ sử dụng ListView có sẵn của Android nó cũng khá là đơn giản.

Đầu tiên mình cũng tạo một file activity_main.xml và thêm vào trong layout một cái Listview như bình thường.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context="com.tuandc.akinosora.listviewexample.MainActivity">


    <ListView
        android:id="@+id/Listview"
        android:layout_width="368dp"
        android:layout_height="495dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Sau đó tại MainActivity.java ta sẽ làm như sau:

package com.tuandc.akinosora.listviewexample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
private ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry",
                "WebOS","Ubuntu","Windows7","Max OS X"};// Tạo mảng chứa các đồi tượng muốn hiển thị.
        listView = (ListView) findViewById(R.id.Listviewex);
        final Adapter adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, mobileArray);// Khởi tạo một ArrayAdapter với các tham số như sau: Activity, Layout item(layout mặc định của hệ thống), mảng các đối tượng.
        listView.setAdapter((ListAdapter) adapter);// gán Adapter vừ tạo cho Listview.
        // Gán sự kiện Click Item cho Listview.
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(MainActivity.this, adapter.getItem(i).toString(), Toast.LENGTH_SHORT).show();// Toast các Item lấy được từ adpter của Listview
            }
        });
    }
}

Kết quả:

Listview trong Android

Listview trong Android

Như các bạn thấy để sử dụng Listview ta cần tạo mảng một chiều các đối tượng muốn hiển thị và tạo một Adapter để gán cái Adapter này cho Listview là ta có thể sự dụng được Listview rồi.

Custom Listview.

Trong thực tế đôi khi nếu chỉ sử dụng Listview Mặc định của Android thôi thì chưa đủ mà đôi khi bạn sẽ cần chỉnh sửa nó để phù hợp với yêu cầu của mình như thêm các hiệu ứng cho các item hay hiển thị Listview theo ý mình muốn….

Vậy để làm nó ta sẽ làm như thế nào.

File activity_main xml thì sẽ không có gì thay đổi và chúng ta sẽ tạo một file xml layout của các item sẽ hiển thị trong Listview.

File item_mobile.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" 
    android:layout_marginTop="10dp">
<ImageView android:layout_width="50dp" android:layout_height="50dp" android:src="@drawable/phone" /> <TextView android:id="@+id/name" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Name" android:textSize="15pt" /> </LinearLayout>

Sau đó ta sẽ tạo thêm một File Adapter khác kế thừa lớp ArrayAdapter

File MobileAdapter

package com.tuandc.akinosora.listviewexample;

import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by Akinosora on 25/09/2017.
 */

public class MobileListAdapter extends ArrayAdapter {
    private Context context_;
    private int resource_;
    private String[] objects_;

    public MobileListAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull String[] objects) {
        super(context, resource, objects);
        this.context_ = context;
        this.resource_ = resource;
        this.objects_ = objects;
    }

    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View inflate = LayoutInflater.from(context_).inflate(resource_, parent, false);// Chuyển đổi File XML ra mã Java
        TextView Name = inflate.findViewById(R.id.name);// ánh xạ các control
        Name.setText(objects_[position]);//gán các dữ liệu lấy từ mảng lên các control
        
        // Gán sự kiên lên các controll trong layout item
        Name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(context_, objects_[position], Toast.LENGTH_SHORT).show();
            }
        });
        return inflate;// trả về View
    }
}

File MainActivity

package com.tuandc.akinosora.listviewexample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {
private ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry",
                "WebOS","Ubuntu","Windows7","Max OS X"};// Tạo mảng chứa các đồi tượng muốn hiển thị.
        listView = (ListView) findViewById(R.id.Listviewex);
        MobileListAdapter adpter = new MobileListAdapter(this, R.layout.item_mobile, mobileArray);// Khởi tạo Adapter
        listView.setAdapter(adpter);
    }
}

Kết quả:

Custom Listview trong Android

Custom Listview trong Android

Như vậy tôi đã giới thiệu với các bạn về cách sử dụng Listview trong Android. Cảm ơn các bạn đã theo dõi và hẹn gặp các bạn trong các chương tiếp theo của Android truyền kì.