Scala で Android アプリ開発(AlertDialog 編)

毎回、AlertDialog を作るのは面倒なので、次のようなオブジェクトを作っておく。

package com.github.cooldaemon.HelloWorld

import _root_.android.content.Context
import _root_.android.app.{Dialog, AlertDialog => AAlertDialog}
import _root_.android.content.DialogInterface

object AlertDialog {
  def create(message: String)(f: () => Unit)(implicit c: Context): Dialog = {
    (new AAlertDialog.Builder(c))
      .setMessage(message)
      .setCancelable(true)
      .setPositiveButton("はい", new DialogInterface.OnClickListener() {
        override def onClick(dialog: DialogInterface, id: Int) {
          f.apply()
          dialog.dismiss()
        }
      })
      .setNegativeButton("いいえ", new DialogInterface.OnClickListener() {
        override def onClick(dialog: DialogInterface, id: Int) {
          dialog.cancel()
        }
      })
      .create()
  }
}

次のように onCreateDialog 内で使用する。

class FooActivity extends TypedActivity {
  // ..snip..

  object DialogID extends Enumeration {
    val WIFI,BLUETOOTH = Value
  }

  override protected def onCreateDialog(id: Int, args: Bundle): Dialog = id match {
    case id if id == DialogID.WIFI.id =>
      AlertDialog.create("Wi-Fi設定を行う") { () =>
        startActivity(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS))
      }
    case id if id == DialogID.BLUETOOTH.id =>
      AlertDialog.create("Bluetooth設定を行う") { () =>
        startActivity(new Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS))
      }
  }

  // ..snip..
}