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

Android AlertDialog에 ListView를 표시하는 방법 완벽 가이드

이 글에서는 Android 앱에서 AlertDialog(경고 대화 상자) 안에 ListView를 표시하는 방법을 단계별 예제 코드와 함께 살펴봅니다. 버튼을 클릭하면 국가 목록이 담긴 대화 상자가 나타나는 간단한 데모를 직접 만들어 보겠습니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File → New Project 메뉴로 이동한 후, 새 프로젝트를 생성하는 데 필요한 모든 정보를 입력해 프로젝트를 만듭니다.

2단계 — activity_main.xml 코드 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 중앙에는 대화 상자를 여는 버튼 하나만 배치했습니다.

<?xml version="1.0" encoding="utf-8"?>
<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/btnClick"
        android:textSize="12sp"
        android:textStyle="bold"
        android:onClick="openDialog"
        android:text="Click here to get ListView in Alert Dialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
</RelativeLayout>

3단계 — MainActivity.java 코드 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다. 여기서 핵심은 LayoutInflater로 커스텀 레이아웃(row.xml)을 불러온 뒤, AlertDialog.BuildersetView() 메서드로 대화 상자에 설정하는 것입니다.

import android.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
    String[] names = {"India", "Brazil", "Argentina",
        "Portugal", "France", "England", "Italy"};
    ArrayAdapter<String> adapter;
    ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void openDialog(View v){
        AlertDialog.Builder alertDialog = new
        AlertDialog.Builder(this);
        View rowList = getLayoutInflater().inflate(R.layout.row, null);
        listView = rowList.findViewById(R.id.listView);
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, names);
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        alertDialog.setView(rowList);
        AlertDialog dialog = alertDialog.create();
        dialog.show();
    }
}

4단계 — 레이아웃 리소스 파일(row.xml) 생성

새 레이아웃 리소스 파일(row.xml)을 만들고 아래 코드를 추가합니다. 이 레이아웃은 ListView와 하단의 'ALL COUNTRIES' 버튼으로 구성되며, 대화 상자 내부에 표시됩니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ALL COUNTRIES"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true" />
    <ListView
        android:id="@+id/listView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_above="@id/button">
    </ListView>
</RelativeLayout>

5단계 — 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 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 목록에서 본인의 모바일 기기를 선택하면 기기에 아래와 같은 기본 화면이 표시됩니다.

Android AlertDialog에 ListView를 표시하는 방법 완벽 가이드

버튼을 클릭하면 ListView가 포함된 AlertDialog가 나타납니다.

Android AlertDialog에 ListView를 표시하는 방법 완벽 가이드

핵심 개념 정리

  • LayoutInflater: XML 레이아웃 파일을 코드에서 사용할 수 있는 View 객체로 변환(inflate)합니다. 대화 상자에 커스텀 레이아웃을 적용할 때 필수적입니다.
  • ArrayAdapter: 문자열 배열 같은 단순 데이터를 ListView 항목에 바인딩하는 가장 기본적인 어댑터입니다.
  • setView(): AlertDialog에 기본 콘텐츠 대신 커스텀 뷰를 지정하는 메서드로, 이를 통해 ListView를 자유롭게 배치할 수 있습니다.