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

KotlinでAndroidアプリのカスタムアラートダイアログを作成する方法【初心者向け解説】

この記事では、Kotlinを使用してAndroidアプリにカスタムアラートダイアログ(Custom Alert Dialog)を実装する手順を、サンプルコードとともにわかりやすく解説します。標準のダイアログではなく、独自のレイアウトを持つダイアログを表示したい場合に役立つ内容です。

ステップ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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="MainActivity">

    <Button
        android:id="@+id/buttonShowCustomDialog"
        style="@android:style/Widget.DeviceDefault.Button.Inset"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="131dp"
        android:onClick="exit"
        android:text="Click"
        android:textStyle="normal|bold" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/buttonShowCustomDialog"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="86dp"
        android:gravity="center"
        android:text="CLICK TO VIEW CUSTOM ALERT DIALOG"
        android:textSize="18sp"
        android:textStyle="normal|bold" />

</RelativeLayout>

ステップ3:MainActivity.kt の実装

続いて、src/MainActivity.kt に以下のコードを記述します。ボタンがタップされると Dialog クラスを使ってカスタムダイアログを生成し、独自のレイアウトファイル(customdialog)をセットして表示します。ダイアログ内の「OK」ボタンを押すとダイアログが閉じられ、トーストメッセージが表示される仕組みです。

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    private val context: Context = this

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
    }

    fun exit(view: View) {
        val dialog = Dialog(context)
        dialog.setContentView(R.layout.customdialog)
        val dialogButton = dialog.findViewById<Button>(R.id.dialogButtonOK)
        dialogButton.setOnClickListener {
            dialog.dismiss()
            Toast.makeText(applicationContext, "Dismissed..!!", Toast.LENGTH_SHORT).show()
        }
        dialog.show()
    }
}

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

androidManifest.xml に以下のコードを追加します。MainActivityがランチャーアクティビティとして正しく登録されていることを確認しましょう。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11">

    <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)アイコンをクリックしてください。

KotlinでAndroidアプリのカスタムアラートダイアログを作成する方法【初心者向け解説】

デバイス選択画面で接続したモバイル端末を選択すると、実機の画面にアプリが起動します。初期画面は以下のようになります。

KotlinでAndroidアプリのカスタムアラートダイアログを作成する方法【初心者向け解説】

画面上のボタンをタップすると、カスタムアラートダイアログが表示されます。ダイアログのデザインや内容は、customdialog.xml レイアウトファイルを編集することで自由にカスタマイズできます。ぜひ、自分好みのダイアログを作成してみてください。

KotlinでAndroidアプリのカスタムアラートダイアログを作成する方法【初心者向け解説】

  1. FacebookでAndroidアプリを作成する方法|開発者サイトでの設定手順を徹底解説

    この記事では、FacebookでAndroidアプリを作成する方法について詳しく解説します。AndroidアプリとFacebookを連携させるには、Facebook開発者サイトでFacebookアプリを作成し、Facebook App IDを取得する必要があります。以下の手順に従って、順番に進めていきましょう。 準備:Facebook開発者サイトで新しいアプリを追加する まず、https://developers.facebook.com/ にアクセスし、「新しいアプリを追加」をクリックしてアプリの作成を開始します。 ステップ1:アプリ名とメールアドレスを入力する 指定されたフィールドに、作

  2. 【Android】XMLファイルを使ってアニメーションを作成する方法をわかりやすく解説

    この記事では、AndroidアプリにおいてXMLファイルを使用してアニメーションを作成する方法を、実際のコード例とともに段階的に解説します。View Animation(Tween Animation)は、res/animディレクトリに配置したリソースファイルとして定義できるため、フェードインやズーム、点滅といった演出をJava側のコードをほとんど書かずに実現できるのが特徴です。 ステップ1:新規プロジェクトの作成 Android Studioを起動し、メニューから「File」⇒「New Project」を選択して新しいプロジェクトを作成します。ウィザードに従って必要な情報を入力し、プロジェク