1
0

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 1 year has passed since last update.

【Android】覚えておくと便利なExtension:Part2

Posted at

はじめに

何かしらの機能で必ず使用するExtensionですが、毎度実装している便利なExtensionを備忘録的に残しておこうと思います。

その1

fun Context.showToast(message: String) {
  mainThread { Toast.makeText(this, message, Toast.LENGTH_SHORT).show()}}

トーストを表示する拡張関数です。
上記はシンプルなデフォルトのトーストを表示する処理ですが、SHORTとLONGで拡張関数分けても良いですね

その2

fun Int.dpToPx(context: Context): Float {
    return this * context.resources.displayMetrics.density
}

fun Int.pxToDp(context: Context): Float {
    return this / context.resources.displayMetrics.density
}

dp、pxをそれぞれ変換するための拡張関数です。
アニメーションさせる際や、画面サイズから何かしたい場合などに使用するケースが多いですよね。

その3

fun String?.isNotNullOrEmpty() = this.isNullOrEmpty().not()

たまにisNullOrEmptyを反転させて条件に当てているのを目にすることがありますが、そんなことをせず拡張関数にすると少しだけスマートです。
反転させた条件は見落としやすいことに対して、こちらは明確なので人為的なミスを防ぐことにもつながりそうです。

さいごに

第二弾でしたが、こういった形でまとめておくと記憶にも残りやすく、微々たるものかもしれませんが探す手間を省くことができそうです。
無駄な時間を減らしてなるべく効率よく業務を進めていく必要があるので、どんどんまとめていこうと思います。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?