Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách thêm phần tử vào ArrayList cho ListView trong Android

Giới thiệu

Ví dụ này minh họa cách chèn phần tử vào ArrayList và hiển thị trên ListView trong ứng dụng Android.

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project, điền đầy đủ thông tin cần thiết để tạo dự án mới.

Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:hint="Nhập tên"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/save"
            android:text="Lưu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/refresh"
            android:text="Làm mới"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ListView>

</LinearLayout>

Trong mã trên, chúng ta sử dụng EditText để nhập tên. Khi người dùng nhấn nút Lưu, dữ liệu sẽ được lưu vào ArrayList. Nhấn nút Làm mới để cập nhật ListView.

Bước 3: Viết logic (src/MainActivity.java)

package com.example.andy.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    Button save, refresh;
    EditText name;
    ArrayAdapter<String> arrayAdapter;
    private ListView listView;
    ArrayList<String> array_list;

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

        array_list = new ArrayList<>();
        name = findViewById(R.id.name);
        listView = findViewById(R.id.listView);

        // Khởi tạo adapter ban đầu
        arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, array_list);
        listView.setAdapter(arrayAdapter);

        findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                arrayAdapter.notifyDataSetChanged();
                listView.invalidateViews();
                listView.refreshDrawableState();
            }
        });

        findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input = name.getText().toString().trim();
                if (!input.isEmpty()) {
                    array_list.add(input);
                    arrayAdapter.notifyDataSetChanged(); // Cập nhật adapter thay vì tạo mới
                    Toast.makeText(MainActivity.this, "Đã thêm", Toast.LENGTH_LONG).show();
                    name.setText(""); // Xóa ô nhập sau khi thêm
                } else {
                    name.setError("Vui lòng nhập tên");
                }
            }
        });
    }
}

Chạy ứng dụng

Kết nối thiết bị Android thật với máy tính. Trong Android Studio, mở file activity và nhấn biểu tượng Run trên thanh công cụ. Chọn thiết bị di động của bạn để chạy ứng dụng.

Cách thêm phần tử vào ArrayList cho ListView trong Android

Trong kết quả trên, chúng ta đang chèn tên vào ArrayList và hiển thị trên ListView.

Lưu ý cải tiến: Trong mã gốc, adapter được tạo mới mỗi lần thêm phần tử. Cách tốt hơn là khởi tạo adapter một lần trong onCreate() và chỉ gọi notifyDataSetChanged() khi dữ liệu thay đổi để tối ưu hiệu suất.