Android
 Computer >> コンピューター >  >> プログラミング >> Android

AndroidのAlertDialogにListViewを表示する方法を徹底解説

この記事では、AndroidのAlertDialog(アラートダイアログ)の中にListViewを表示する方法を、実際に動作するサンプルコードとともに段階的に解説します。ボタンをタップするとダイアログが開き、国名の一覧がリスト形式で表示されるシンプルなアプリを構築していきます。

手順1:新規プロジェクトの作成

Android Studioを起動し、メニューから「File」⇒「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成してください。

手順2:activity_main.xmlにコードを追加

res/layout/activity_main.xml に以下のコードを記述します。画面中央に配置されたボタンをタップすると、onClick属性で指定した openDialog メソッドが呼び出される仕組みです。

<?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 に以下のコードを追加します。

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();
    }
}

実装のポイント

  • LayoutInflater:getLayoutInflater().inflate() を使って、ダイアログ用のカスタムレイアウト(row.xml)を読み込みます。
  • ArrayAdapter:標準レイアウト android.R.layout.simple_list_item_1 を利用し、国名の文字列配列をListViewにバインドします。
  • setView():alertDialog.setView(rowList) を呼び出すことで、通常のメッセージやボタンだけでなく、自由なレイアウトをダイアログ内に表示できます。

手順4:ダイアログ用レイアウト(row.xml)の作成

layoutリソースファイルとして 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を表示する方法を徹底解説

AndroidのAlertDialogにListViewを表示する方法を徹底解説

ボタンをタップすると、ListViewを含んだアラートダイアログが表示され、国名の一覧をスクロールしながら確認できます。この手法を応用すれば、選択肢が多い設定項目やデータ一覧を、別画面に遷移することなくダイアログ内で直感的に提示できるようになります。

  1. 【Android開発入門】トースト(Toast)を表示する方法をステップ解説

    Androidでトーストを表示するには?この記事では、Androidアプリでトースト(Toast)を表示する方法を、実際のコード例とともにわかりやすく解説します。トーストとは、画面の下部に短時間だけ表示される小さなポップアップメッセージのことで、ユーザーへの簡単な通知やフィードバックに活用されます。それでは、具体的な手順を見ていきましょう。ステップ1:新規プロジェクトを作成するまず、Android Studioを起動し、メニューから「File」→「New Project」を選択して、必要な情報を入力して新しいプロジェクトを作成します。ステップ2:レイアウトファイルにコードを追加する次に、res

  2. Androidでアクティビティ起動前にプログレスダイアログを表示する方法

    このチュートリアルでは、Androidアプリでアクティビティを起動する前にプログレスダイアログ(進行状況ダイアログ)を表示する方法を、実際のコード例とともにわかりやすく解説します。 実装のポイント ポイントは AsyncTask の onPreExecute() メソッド内でダイアログを表示することです。onPreExecute() はバックグラウンド処理が始まる直前にメインスレッド上で呼び出されるため、このタイミングで progressDialog.show() を呼び出せば、読み込み中であることをユーザーに伝えられます。 補足: ProgressDialog は API レベル 26 以降