【Kotlin/Android Studio】AlertDialogの使い方!DialogFragmentでカスタムダイアログ

この記事からわかること

  • Android Studio/KotlinAlertDialog使い方
  • アプリダイアログ(ポップアップビュー)を実装する方法
  • リストチェックボックスラジオボタンなど
  • DialogFragmentカスタムダイアログを作成するには?

index

[open]

\ アプリをリリースしました /

みんなの誕生日

友達や家族の誕生日をメモ!通知も届く-みんなの誕生日-

posted withアプリーチ

環境

AlertDialogでダイアログを実装する方法

Androidでダイアログ(ポップアップビュー)を実装するにはAlertDialogクラスを使用します。実装方法は簡単で「MainActivity.kt」にコードを書くだけで実装することが可能です。今回はボタンをタップされた時にダイアログが出る仕組みを実装していきます。まずはその前に「activity_main.xml」にボタンを設置しておきます。


<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/done_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Done"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

シンプルなダイアログ

まずはシンプルなダイアログを実装して使い方をみていきます。AlertDialogクラスからBuilderを呼び出し、引数にはContext(ここではthis)を渡します。そこからsetTitleメソッドでタイトルsetMessageメソッドでメッセージsetPositiveButtonメソッドでボタンを定義します。最後にshowメソッドを実行することでダイアログが表示されます。

val button:Button = findViewById(R.id.done_button)

button.setOnClickListener {
    AlertDialog.Builder(this)
            .setTitle("ここにタイトル")
            .setMessage("ダイアログのメッセージ")
            .setPositiveButton("OK", { dialog, which ->
                // ボタンクリック時の処理
            })
            .show()
}
【Kotlin/Android Studio】AlertDialogの使い方!DialogFragmentでカスタムダイアログ

アイコンをつける

setIconメソッドを使用することでダイアログに画像(アイコン)を設置することができます。

val button:Button = findViewById(R.id.done_button)

button.setOnClickListener {
    AlertDialog.Builder(this)
            .setTitle("ここにタイトル")
            .setMessage("ダイアログのメッセージ")
            .setPositiveButton("OK", { dialog, which ->
                // ボタンクリック時の処理
            })
            .setIcon(R.mipmap.ic_launcher)
            .show()
}
【Kotlin/Android Studio】AlertDialogの使い方!DialogFragmentでカスタムダイアログ

ボタンを2つ表示する

ボタンを2つ表示するにはsetPositiveButtonメソッドとsetNegativeButtonメソッドを使用します。setPositiveButtonメソッドで指定した方が右側にsetNegativeButtonメソッドが左側に来るように配置されます。

AlertDialog.Builder(this)
    .setTitle("ここにタイトル")
    .setMessage("ダイアログのメッセージ")
    .setPositiveButton("OK", { dialog, which ->
        // ボタンクリック時の処理
    })
    .setNegativeButton("キャンセル", { dialog, which ->
    // ボタンクリック時の処理
    })
    .show()
【Kotlin/Android Studio】AlertDialogの使い方!DialogFragmentでカスタムダイアログ

3つ目のボタンを表示する

setNeutralButtonメソッドを使用することで3つ目のボタンを設置することができます。これはダイアログの左側に配置されます。3つ目と書きましたが、ボタンの定義が1つしかない状態でsetNeutralButtonメソッドを使用しても変わらずダイアログの左側に配置されます。

AlertDialog.Builder(this)
    .setTitle("ここにタイトル")
    .setMessage("ダイアログのメッセージ")
    .setPositiveButton("OK", { dialog, which ->
        // ボタンクリック時の処理
    })
    .setNegativeButton("キャンセル", { dialog, which ->
    // ボタンクリック時の処理
    })
    .setNeutralButton("その他", { dialog, which ->
        // ボタンクリック時の処理
    })
    .show()
【Kotlin/Android Studio】AlertDialogの使い方!DialogFragmentでカスタムダイアログ

ダイアログでリストを表示する

ダイアログ内でリストを表示するにはsetItemsメソッドを使用します。引数に表示させたいリストを渡します。

val list = arrayOf("kotlin","Swift","Dart")
AlertDialog.Builder(this)
    .setTitle("アプリ開発言語")
    .setItems(list, { dialog, which ->
        // ボタンクリック時の処理
    })
    .setPositiveButton("OK", { dialog, which ->
        // ボタンクリック時の処理
    })
    .show()
【Kotlin/Android Studio】AlertDialogの使い方!DialogFragmentでカスタムダイアログ

ダイアログでチェックボックスを表示する

ダイアログ内でチェックボックスを表示するにはsetMultiChoiceItemsメソッドを使用します。引数に表示させたいリストとチェックフラグを渡します。

val list = arrayOf("kotlin","Swift","Dart")
val checkedFlags = booleanArrayOf(true, false, false)
AlertDialog.Builder(this)
    .setTitle("アプリ開発言語")
    .setMultiChoiceItems(list, checkedFlags, { dialog, which, isChecked ->
        // ボタンクリック時の処理
    })
    .setPositiveButton("OK", { dialog, which ->
        // ボタンクリック時の処理
    })
    .show()
【Kotlin/Android Studio】AlertDialogの使い方!DialogFragmentでカスタムダイアログ

ダイアログでラジオボタンを表示する

ダイアログ内でラジオボタンを表示するにはsetMultiChoiceItemsメソッドを使用します。引数に表示させたいリストとデフォルトでチェック状態にするインデックス番号を渡します。

val list = arrayOf("kotlin","Swift","Dart")
AlertDialog.Builder(this)
    .setTitle("アプリ開発言語")
    .setSingleChoiceItems(list, 0, { dialog, which ->
        // ボタンクリック時の処理
    })
    .setPositiveButton("OK", { dialog, which ->
        // ボタンクリック時の処理
    })
    .show()
【Kotlin/Android Studio】AlertDialogの使い方!DialogFragmentでカスタムダイアログ

カスタムダイアログ:DialogFragment

まずはDialogFragmentを使用してFragment側にダイアログの処理を移してみます。まずは適当にCustomDialogFragmentを作成します。DialogFragmentを継承させ、onCreateDialogメソッド内でダイアログ構築処理を実装し、最後にbuilder.create()を実行し返します。

import android.app.Dialog
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment

class CustomDialogFragment: DialogFragment() {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val builder = AlertDialog.Builder(this.requireContext())
        builder.setTitle("ここにタイトル")
            .setMessage("ダイアログのメッセージ")
            .setPositiveButton("OK", { dialog, which ->
                // ボタンクリック時の処理
            })
            .show()

        return builder.create()
    }
}

あとは「MainActivity.kt」側から以下のようにすっきりと呼び出すことができるようになります。

val button:Button = findViewById(R.id.done_button)
button.setOnClickListener{
    val dialog = CustomDialogFragment()
    dialog.show(supportFragmentManager, "custom")
}
【Kotlin/Android Studio】AlertDialogの使い方!DialogFragmentでカスタムダイアログ

独自のレイアウトダイアログを作成する

ダイアログの中身を独自にカスタマイズしたものを実装するにはレイアウトファイルを用意し、それをダイアログとして表示させる方法で実現できます。まずは以下のように適当なレイアウトファイルを用意します。


<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/editTextText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="text"
        android:text="Name"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextText" />
</androidx.constraintlayout.widget.ConstraintLayout>

続いてCustomDialogFragmentクラスのonCreateDialogメソッド内で以下のようにdialog_fragmentレイアウトをインフレートしsetViewメソッドでAlertDialog.Builderインスタンスに渡します。


class CustomDialogFragment: DialogFragment() {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

        val builder = AlertDialog.Builder(this.requireContext())
        val inflater = this.requireActivity().layoutInflater
        val dialog = inflater.inflate(R.layout.dialog_fragment,null)

        builder.setView(dialog)
        return builder.create()
    }
}

最後にMainActivityクラスでCustomDialogFragmentクラスをインスタンス化しshowメソッドを呼び出すことで実装できます。


 val button:Button = findViewById(R.id.done_button)
button.setOnClickListener{
    val dialog = CustomDialogFragment()
    dialog.show(supportFragmentManager, "custom")
}
【Kotlin/Android Studio】AlertDialogの使い方!DialogFragmentでカスタムダイアログ

まだまだ勉強中ですので間違っている点や至らぬ点がありましたら教えていただけると助かります。

ご覧いただきありがとうございました。

searchbox

スポンサー

ProFile

ame

趣味:読書,プログラミング学習,サイト制作,ブログ

IT嫌いを克服するためにITパスを取得しようと勉強してからサイト制作が趣味に変わりました笑
今はCMSを使わずこのサイトを完全自作でサイト運営中〜

New Article

index