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

KotlinでAndroidにタイトルなしのダイアログボックスを作成する方法

この記事では、Kotlinを使ってAndroidアプリでタイトルバーのないダイアログボックス(AlertDialog)を作成する手順を、サンプルコード付きでわかりやすく解説します。通常のAlertDialogはデフォルトでタイトル領域が表示されますが、Builderでタイトルを設定しないことで、メッセージとボタンだけのシンプルなダイアログを実現できます。

完成イメージ

アプリを起動すると、画面中央に「Alert Dialog without title」というテキストが表示され、同時にタイトルのないアラートダイアログが立ち上がります。「Yes」を押すとダイアログが閉じられ、トーストで完了メッセージが表示されます。

ステップ1:新規プロジェクトを作成する

Android Studioを開き、File → New Project を選択して新しいプロジェクトを作成します。必要な項目(プロジェクト名、パッケージ名、保存先など)を入力し、Empty Activityテンプレートを選んでプロジェクトを生成してください。言語はKotlinを選択します。

ステップ2:レイアウトファイル(activity_main.xml)を編集する

res/layout/activity_main.xml に以下のコードを追加します。背景色付きのTextViewと、画面中央に配置された説明用テキストを含むシンプルなレイアウトです。

<?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">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="70dp"
        android:background="#008080"
        android:padding="5dp"
        android:text="TutorialsPoint"
        android:textColor="#fff"
        android:textSize="24sp"
        android:textStyle="bold" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Alert Dialog without title"
        android:textAlignment="center"
        android:textColor="@android:color/holo_orange_dark"
        android:textSize="24sp"
        android:textStyle="bold" />

</RelativeLayout>

ステップ3:MainActivity.ktにダイアログ処理を記述する

src/MainActivity.kt に以下のコードを追加します。ポイントは AlertDialog.Builder を使う際に setTitle() を呼び出さないことです。これにより、タイトル領域を持たないダイアログが生成されます。

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity

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

        val builder = AlertDialog.Builder(this)
        builder.setMessage("Do you want to close the alert dialog without title?")

        builder.setPositiveButton("Yes") { dialog, _ ->
            dialog.cancel()
            Toast.makeText(applicationContext, "Your dialog has been closed", Toast.LENGTH_LONG)
                .show()
        }

        builder.setNegativeButton("No") { _, _ -> }

        val alertDialog: AlertDialog = builder.create()
        alertDialog.show()
    }
}

コードの解説

  • AlertDialog.Builder(this):アクティビティのコンテキストを渡してビルダーを生成します。
  • setMessage():ダイアログ本文に表示するメッセージを設定します。
  • setPositiveButton():「Yes」ボタン押下時にダイアログを閉じ、Toastで通知を表示します。
  • setNegativeButton():「No」ボタンは何もせずに閉じるだけの空実装です。
  • builder.create() → 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スマートフォンをPCに接続していることを前提に説明します。Android Studioでプロジェクト内の任意のアクティビティファイルを開き、ツールバーのRun(実行)アイコンをクリックしてください。接続したモバイル端末を選択すると、実機の画面にアプリが起動し、タイトルのないアラートダイアログが表示されます。

KotlinでAndroidにタイトルなしのダイアログボックスを作成する方法

KotlinでAndroidにタイトルなしのダイアログボックスを作成する方法

まとめ

Kotlinでタイトルなしのダイアログを作るのは非常に簡単です。AlertDialog.Builderに対してsetTitle()を呼び出さず、setMessage()だけでメッセージを設定すれば、メッセージとボタンのみのミニマルなダイアログが表示されます。確認ダイアログや簡易的な通知など、余計な装飾を省きたい場面でぜひ活用してみてください。

  1. Androidでニュートラルオプション付きのダイアログ(AlertDialog)を作成する方法

    はじめに本記事では、Androidアプリでニュートラル(Neutral)オプションを含むダイアログを作成する方法を解説します。AlertDialogでは、肯定を表すPositiveButtonや否定を表すNegativeButtonに加えて、中立の役割を担う第3のボタン「NeutralButton」を設定できます。これにより、ユーザーにより柔軟な選択肢を提供することが可能になります。ステップ1:新規プロジェクトを作成するAndroid Studioを開き、「File」→「New Project」を選択して、必要な項目を入力し、新しいプロジェクトを作成します。ステップ2:レイアウトファイルを編集

  2. Androidでカスタムダイアログボックスを作成する方法を徹底解説!初心者向けステップガイド

    この記事では、Androidアプリでカスタムメッセージダイアログを作成する方法を、ステップごとにわかりやすく解説します。独自レイアウトのダイアログを活用すれば、ユーザーにテキスト入力を促すUIなど、標準のAlertDialogでは実現できない柔軟なデザインが可能になります。 完成するアプリの動作イメージ メイン画面の「Show Message」ボタンをタップするとカスタムダイアログが表示され、メッセージを入力して「Okay」を押すと、その内容が画面上部のTextViewに反映されます。「Cancel」を押した場合は、入力内容を破棄してダイアログが閉じられます。 手順1:Android Stud