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

【Android】カスタムAlertDialogビューを実装する完全ガイド

この記事では、AndroidアプリでカスタムAlertDialog(ダイアログ)を実装する方法を、サンプルコード付きで段階的に解説します。標準的なダイアログではなく、独自のレイアウトを持つダイアログを表示したい場合に役立つ内容です。

ステップ1:新規プロジェクトの作成

まず、Android Studioを起動し、「File」⇒「New Project」を選択して新しいプロジェクトを作成します。必要な項目をすべて入力してプロジェクトの雛形を生成しましょう。

ステップ2:activity_main.xml にコードを追加

res/layout/activity_main.xml に以下のコードを記述します。画面中央に配置されたボタンが、ダイアログを表示するトリガーになります。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
   xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:app="https://schemas.android.com/apk/res-auto"
   xmlns:tools="https://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <Button
      android:id="@+id/buttonShowDialog"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:background="@color/colorPrimary"
      android:padding="15dp"
      android:text="Android Custom Dialog Example"
      android:textAllCaps="false"
      android:textColor="#ffffff" />
</androidx.constraintlayout.widget.ConstraintLayout>

ステップ3:my_dialog.xml(ダイアログ用レイアウト)を作成

次に、res/layout/my_dialog.xml を新規作成し、以下のコードを追加します。このレイアウトが、ダイアログ上に表示されるカスタムビューの本体です。成功アイコン・タイトル・説明文・OKボタンを縦に並べたシンプルな構成になっています。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
   <RelativeLayout
      android:layout_width="match_parent"
      android:layout_height="80dp"
      android:background="@color/colorPrimary">
      <ImageView
         android:layout_width="50dp"
         android:layout_height="50dp"
         android:layout_centerInParent="true"
         android:background="@drawable/ic_success" />
   </RelativeLayout>
   <TextView
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="Success"
      android:textAlignment="center"
      android:textAppearance="@style/TextAppearance.AppCompat.Headline"/>
   <TextView
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginTop="10dp"
      android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit.
      Nulla eu erat tincidunt lacus fermentum rutrum."
      android:textAlignment="center"
      android:textAppearance="@style/TextAppearance.AppCompat.Medium"/>
   <Button
      android:id="@+id/buttonOk"
      android:layout_width="200dp"
      android:layout_height="wrap_content"
      android:layout_gravity="center"
      android:layout_marginTop="15dp"
      android:background="@drawable/button_background"
      android:text="Ok"
      android:textColor="@color/colorPrimary" />
</LinearLayout>

ステップ4:button_background.xml(ボタンの背景)を作成

res/drawable/button_background.xml を作成し、以下のコードを追加します。枠線付きの角丸ボタンを定義するセレクタです。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
   <item>
      <shape>
         <stroke android:width="2dp" android:color="@color/colorPrimary" />
         <solid android:color="@android:color/transparent" />
         <corners android:bottomLeftRadius="6dp" android:bottomRightRadius="6dp" android:topLeftRadius="6dp" android:topRightRadius="6dp" />
      </shape>
   </item>
</selector>

ステップ5:ic_success.xml(成功アイコン)を作成

res/drawable/ic_success.xml を作成し、以下のベクター画像のコードを追加します。チェックマーク入りの円形アイコンを描画しています。

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="https://schemas.android.com/apk/res/android"
   android:height="24dp"
   android:viewportHeight="512"
   android:viewportWidth="512"
   android:width="24dp">
   <path android:fillColor="#FFFFFF" android:pathData="M468.907,214.604c-11.423,0 -20.682,9.26
      -20.682,20.682v20.831c-0.031,54.338 -21.221,105.412 -59.666,143.812c38.417,38.372
      -89.467,59.5 -143.761,59.5c-0.04,0 -0.08,0 -0.12,0C132.506,459.365 41.3,368.056 41.364,255.883c0.031,
      -54.337 21.221,-105.411 59.667,-143.813c38.417,- 38.372 89.468,-59.5 143.761,
      -59.5c0.04,0 0.08,0 0.12,0c28.672,0.016 56.49,5.942 82.68,17.611c10.436,4.65 22.659,
      -0.041 27.309,-10.474c4.648,-10.433 -0.04,-22.659 - 10.474,-27.309c-31.516,-14.043
      -64.989,-21.173 -99.492,-21.192c-0.052,0 -0.092,0 - 0.144,0c-65.329,0 -126.767,25.428
      -172.993,71.6C25.536,129.014 0.038,190.473 0,255.861c-0.037,65.386 25.389,126.874 71.599,
      173.136c46.21,46.262 107.668,71.76 173.055,71.798c0.051,0 0.092,0 0.144,0c65.329,0 126.767,
      -25.427 172.993,-71.6c46.262,-46.20971.76,-107.66871.798,-173.066v20.842C489.589,
      223.864 480.33,214.604 468.907,214.604z"/>
   <path android:fillColor="#FFFFFF" android:pathData="M505.942,39.803c-8.077,- 8.076 -21.172,-8.076
      -29.249,0L244.794,271.701l-52.609,-52.609c-8.076,-8.077 -21.172,-8.077 -29.248,0c-8.077,8.077
      -8.077,21.172 0,29.249l67.234,67.234c4.038,4.0399.332,6.058 14.625,6.058c5.293,0 10.586,-2.019 14.625,
      -6.058L505.942,69.052C514.019,60.975 514.019,47.88 505.942,39.803z"/>
</vector>

ステップ6:MainActivity.java にダイアログ表示処理を追加

src/MainActivity.java に以下のコードを記述します。ポイントは、LayoutInflater を使ってカスタムレイアウト(my_dialog.xml)をinflateし、それを AlertDialog.BuildersetView() に渡すところです。

package com.app.sample;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      findViewById(R.id.buttonShowDialog).setOnClickListener(new
      View.OnClickListener() {
         @Override
         public void onClick(View v) {
            showCustomDialog();
         }
      });
   }
   private void showCustomDialog() {
      ViewGroup viewGroup = findViewById(android.R.id.content);
      View dialogView = LayoutInflater.from(this).inflate(R.layout.my_dialog, viewGroup, false);
      AlertDialog.Builder builder = new AlertDialog.Builder(this);
      builder.setView(dialogView);
      AlertDialog alertDialog = builder.create();
      alertDialog.show();
   }
}

このコードでは、ボタンがクリックされると showCustomDialog() メソッドが呼び出され、独自レイアウトを組み込んだAlertDialogが画面に表示されます。

ステップ7:AndroidManifest.xml の確認

Manifests/AndroidManifest.xml に以下のコードを追加します。MainActivityをランチャーアクティビティとして登録しています。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.app.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)アイコンをクリックします。オプションとして自分のモバイルデバイスを選択してください。

その後、実機の画面を確認すると、まずデフォルトの画面が表示されます。ボタンをタップすれば、作成したカスタムダイアログが立ち上がり、成功アイコンとメッセージ、OKボタンが表示されるはずです。

【Android】カスタムAlertDialogビューを実装する完全ガイド


  1. AndroidのActionBarにカスタムビューを表示する方法をステップ解説

    ActionBarにカスタムビューを表示するには? このチュートリアルでは、AndroidアプリのActionBar(アクションバー)に独自のカスタムビューを表示する方法を、サンプルコードとともに解説します。 カスタムビューを活用すれば、デフォルトのタイトル表示だけでは実現できない、ロゴやタイトル、アイコンを自由に配置したオリジナルのヘッダーを作成できます。 実装手順 ステップ1:新規プロジェクトを作成する Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。 ステップ2:res

  2. AndroidのカスタムListViewに検索機能を実装する方法【サンプルコード付き】

    はじめに このチュートリアルでは、AndroidアプリのListView(リストビュー)に検索機能を実装する方法を解説します。EditTextに入力した文字列に応じて、表示中のリスト項目をリアルタイムで絞り込む仕組みを作成します。 手順1:新規プロジェクトを作成する Android Studioを開き、「File」→「New Project」を選択して、必要な項目をすべて入力し、新しいプロジェクトを作成します。 手順2:レイアウトファイル(activity_main.xml)を編集する res/layout/activity_main.xml に以下のコードを記述します。上部に検索ワードを入力