Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드에서 ListView를 동적으로 업데이트하는 방법 (단계별 코드 예제)

이 튜토리얼에서는 안드로이드 앱에서 ListView를 동적으로 업데이트하는 방법을 단계별로 살펴봅니다. 사용자가 EditText에 항목을 입력하고 버튼을 누르면 해당 항목이 ListView에 실시간으로 추가되는 간단한 예제를 함께 만들어 보겠습니다.

핵심 원리는 매우 간단합니다. 데이터 목록(ArrayList)에 새 값을 추가한 뒤, 어댑터의 notifyDataSetChanged() 메서드를 호출하면 ListView가 변경된 데이터를 자동으로 다시 그려줍니다.


1단계: 새 프로젝트 생성

Android Studio를 실행한 후 File → New Project를 선택하고, 프로젝트 생성에 필요한 모든 정보를 입력하여 새 프로젝트를 만듭니다.

2단계: 레이아웃 작성 — res/layout/activity_main.xml

아래 코드를 res/layout/activity_main.xml 파일에 추가합니다. 화면 상단에는 입력창(EditText)과 '항목 추가' 버튼(Button)이 배치되고, 그 아래에 ListView가 위치하도록 구성했습니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="4dp"
    android:orientation="vertical" >
    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:hint="Enter an item here" />
    <Button
        android:id="@+id/btnAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add item"
        android:layout_below="@id/editText" />
    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/btnAdd" />
</RelativeLayout>

3단계: 메인 액티비티 작성 — src/MainActivity.java

다음으로 src/MainActivity.java 파일에 아래 코드를 추가합니다. 버튼을 클릭하면 EditText에 입력된 값이 ArrayList에 추가되고, 어댑터에 데이터 변경 사항을 알려 ListView를 갱신하는 것이 이 예제의 핵심 로직입니다.

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
    EditText editText;
    Button button;
    ListView listView;
    ArrayList<String> list = new ArrayList<>();
    ArrayAdapter<String> adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.btnAdd);
        listView = findViewById(R.id.listView);
        editText = findViewById(R.id.editText);
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.add(editText.getText().toString());
                editText.setText("");
                adapter.notifyDataSetChanged();
            }
        };
        button.setOnClickListener(onClickListener);
        listView.setAdapter(adapter);
    }
}

4단계: 매니페스트 설정 — androidManifest.xml

마지막으로 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>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 안드로이드에서 ListView를 동적으로 업데이트하는 방법 (단계별 코드 예제) 아이콘을 클릭하세요. 실행 옵션에서 본인의 모바일 기기를 선택하면, 기기에 아래와 같은 기본 화면이 표시됩니다.

안드로이드에서 ListView를 동적으로 업데이트하는 방법 (단계별 코드 예제)

입력창에 원하는 항목을 입력하고 Add item 버튼을 누를 때마다 새 항목이 ListView 맨 아래에 즉시 추가되는 것을 확인할 수 있습니다.

핵심 포인트 정리

  • ArrayAdapter — ArrayList 데이터와 ListView UI를 연결해 주는 어댑터입니다.
  • notifyDataSetChanged() — 데이터가 변경되었음을 어댑터에 알려 ListView를 다시 그리도록 하는 필수 호출입니다. 이를 생략하면 화면이 갱신되지 않습니다.
  • 입력창 초기화 — 항목 추가 후 editText.setText("")로 입력창을 비워 사용자 편의성을 높였습니다.