20
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Android開発で便利な拡張関数

Last updated at Posted at 2017-08-21

#Android開発で便利な拡張関数
Kotlinを使ってみて拡張関数がとても便利だったので、
Android開発のときに定義している拡張関数をメモ。
##トースト
簡単にトーストを出す。

utils.kt
private val uiHandler = Handler(Looper.getMainLooper())
//UIスレッドで実行
fun mainThread(runnable: () -> Unit) {
  uiHandler.post(runnable)}

//短いトースト
fun Context.toast(message: String) {
  mainThread { Toast.makeText(this, message, Toast.LENGTH_SHORT).show()}}

//長いトースト
fun Context.longToast(message: String) {
  mainThread { Toast.makeText(this, message, Toast.LENGTH_LONG).show()}}

##インテント

utils.kt
//インテントを作成
inline fun <reified T : Context> Context.newIntent(): Intent = Intent(this, T::class.java)

//Bundle付き
inline fun <reified T : Context> Context.newIntent(extras: Bundle): Intent = newIntent<T>(0, extras)

//インテントを定義してアクティビティを起動
inline fun <reified T : Activity> Activity.startActivity(): Unit =this.startActivity(newIntent<T>())
HogeActivity.kt
val intent=newIntent<FooActivity>()

start<FooActivity>()

##システムサービス
getSystemServiceのテンプレコードも楽に書ける。

utils.kt
fun Context.getActivityManager(): ActivityManager =
        getSystemServiceAs(Context.ACTIVITY_SERVICE)

fun Context.getClipboardManager(): ClipboardManager =
        getSystemServiceAs(Context.CLIPBOARD_SERVICE)

fun Context.getCameraManager(): CameraManager =
        getSystemServiceAs(Context.CAMERA_SERVICE)

fun Context.getNotificationManager(): NotificationManager =
        getSystemServiceAs(Context.NOTIFICATION_SERVICE)

@Suppress("UNCHECKED_CAST")
fun <T> Context.getSystemServiceAs(serviceName: String): T =
        this.getSystemService(serviceName) as T

##API判定

utils.kt
private val version: Int
    get() = Build.VERSION.SDK_INT

fun fromApi(fromVersion: Int, inclusive: Boolean = true, action: () -> Unit) {
    if (version > fromVersion || (inclusive && version == fromVersion)) action()
}
HogeActivity.kt
fromApi(23){
//パーミッションの処理などに使える
}

##まとめ
よく使うのはこの辺り。
他にも便利な定義知ってるよって人は教えて欲しいです。

20
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?