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

Thêm phần tử động vào ListView Android

Thêm phần tử động vào ListView Android

Hướng dẫn này minh họa cách thêm các mục mới vào ListView tại runtime khi người dùng nhập liệu.

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

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

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

<RelativeLayout 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">
    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:text="Add Values to listView" />
    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="26dp"
        android:ems="10"
        android:hint="Add elements listView" />
    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_centerHorizontal="true">
    </ListView>
</RelativeLayout>

Bước 3: Code MainActivity.java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends Activity {
    ListView listview;
    Button addButton;
    EditText GetValue;
    String[] ListElements = new String[] { "Android", "PHP", "Python" };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        listview = findViewById(R.id.listView1);
        addButton = findViewById(R.id.button1);
        GetValue = findViewById(R.id.editText1);
        
        final List<String> ListElementsArrayList = new ArrayList<>(Arrays.asList(ListElements));
        final ArrayAdapter<String> adapter = new ArrayAdapter<>(
            MainActivity.this, android.R.layout.simple_list_item_1, ListElementsArrayList);
        
        listview.setAdapter(adapter);
        
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newItem = GetValue.getText().toString().trim();
                if (!newItem.isEmpty()) {
                    ListElementsArrayList.add(newItem);
                    adapter.notifyDataSetChanged();
                    GetValue.setText(""); // Xóa ô nhập sau khi thêm
                }
            }
        });
    }
}

Bước 4: Cấu hình AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, chạy app. Nhập văn bản vào EditText, nhấn "Add Values to listView" để thêm mục mới vào ListView. Danh sách sẽ cập nhật ngay lập tức nhờ notifyDataSetChanged().

Điểm quan trọng: Luôn gọi adapter.notifyDataSetChanged() sau khi thay đổi dữ liệu nguồn (ArrayList) để ListView cập nhật giao diện.