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

【Android開発】角丸デザインのカスタムダイアログを作成する方法をわかりやすく解説

この記事では、Androidアプリで角が丸い(角丸)カスタムダイアログを実装する方法を、サンプルコードとともに段階的に解説します。標準のAlertDialogでは実現できないオリジナルデザインのダイアログを作りたい方は、ぜひ参考にしてください。

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

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

手順2:レイアウトファイル(activity_main.xml)の編集

res/layout/activity_main.xml に以下のコードを追加します。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/parent"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:gravity="center"
    android:orientation="vertical">
    <Button
        android:id="@+id/customDialog"
        android:text="Custom Dialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

このコードでは、ボタンを1つ配置しています。ユーザーがこのボタンをタップすると、カスタムダイアログが表示される仕組みです。

手順3:MainActivity.java の実装

次に、src/MainActivity.java に以下のコードを記述します。

package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.customDialog).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this,R.style.CustomAlertDialog);
                ViewGroup viewGroup = findViewById(android.R.id.content);
                View dialogView = LayoutInflater.from(v.getContext()).inflate(R.layout.customview, viewGroup, false);
                Button buttonOk=dialogView.findViewById(R.id.buttonOk);
                builder.setView(dialogView);
                final AlertDialog alertDialog = builder.create();
                buttonOk.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alertDialog.dismiss();
                    }
                });
                alertDialog.show();
            }
        });
    }
}

ここでのポイントは、LayoutInflaterを使って独自のビュー(customview)をインフレートし、AlertDialogにセットしている点です。これにより、自由にデザインしたダイアログを表示できます。

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

ダイアログの内容を定義するため、customview.xml を作成し、以下のコードを追加します。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp">
        <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="@color/colorPrimary"
            android:text="Ok"
            android:textColor="#FFF" />
    </LinearLayout>
</LinearLayout>

このレイアウトには、タイトル用・本文用のTextViewと、「OK」ボタンが含まれています。

手順5:カスタムテーマの適用(styles.xml)

先ほどのMainActivity.javaでは、AlertDialog.Builderの第2引数にカスタムテーマを指定しました。

final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this,R.style.CustomAlertDialog);

そこで、res/values/styles.xml に以下のスタイルを定義します。

<style name="CustomAlertDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:windowBackground">@drawable/popup_background</item>
</style>

このコードでは、ダイアログの背景として popup_background を指定しています。角丸を実現する鍵は、この背景drawableにあるのです。

手順6:角丸背景の作成(popup_background.xml)

drawableフォルダ内に popup_background.xml を作成し、以下のコードを追加します。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF" />
    <corners android:radius="6dp" />
</shape>

shapeタグの corners 要素で radius(角の半径)を指定することで、背景が角丸の白いダイアログになります。radiusの値を変更すれば、角の丸みを好みに調整できます。

実行結果の確認

それでは、アプリを実行してみましょう。実機のAndroidスマートフォンをパソコンに接続し、Android Studioでプロジェクト内のアクティビティファイルを開いて、ツールバーの「Run」アイコンをクリックします。デバイスを選択して実行すると、まず初期画面が表示されます。

【Android開発】角丸デザインのカスタムダイアログを作成する方法をわかりやすく解説

初期画面のボタンをタップすると、以下のように角丸デザインのカスタムダイアログが表示されます。

【Android開発】角丸デザインのカスタムダイアログを作成する方法をわかりやすく解説

まとめ

Androidで角丸のカスタムダイアログを作るには、①独自レイアウトをインフレートしてAlertDialogにセットし、②styles.xmlでカスタムテーマを定義し、③windowBackgroundにcornersを含むshape drawableを指定する、という流れになります。radiusの値や背景色を変えるだけで、さまざまなデザインに応用できるので、プロジェクトのUIに合わせてカスタマイズしてみてください。

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

    この記事では、AndroidアプリでカスタムAlertDialog(ダイアログ)を実装する方法を、サンプルコード付きで段階的に解説します。標準的なダイアログではなく、独自のレイアウトを持つダイアログを表示したい場合に役立つ内容です。 ステップ1:新規プロジェクトの作成 まず、Android Studioを起動し、「File」⇒「New Project」を選択して新しいプロジェクトを作成します。必要な項目をすべて入力してプロジェクトの雛形を生成しましょう。 ステップ2:activity_main.xml にコードを追加 res/layout/activity_main.xml に以下のコードを記

  2. 【Android】ボタンの角を丸くする方法を徹底解説!カスタムドローアブルで実装する手順

    このチュートリアルでは、Androidアプリでボタンの角を丸く表示する方法を、実際のコード例とともにわかりやすく解説します。カスタムドローアブル(Drawable)を活用することで、通常時・フォーカス時・押下時といったボタンの状態に応じた角丸デザインも柔軟に実現できます。 手順1:Android Studioで新規プロジェクトを作成する まずはAndroid Studioを起動し、メニューから「File → New Project」を選択して新しいプロジェクトを作成しましょう。必要な項目をすべて入力し、プロジェクトのセットアップを完了させてください。 手順2:レイアウトファイル(activit