Android SDKにいくつかの大まかな側面があり、それは秘密ではありません。

あなたがAndroidの初心者で、画像を表示しようとしていると想像してください。あなたはすでにresフォルダに画像を追加しているので、今度はDrawableを入手する必要があります。 outresources.getDrawable()は、推奨されなくなり、置き換えられる関数がLollipop以上でのみ利用可能であることを確認するためだけに作成します。あなたがプレロリポップをサポートする必要があるなら、あなたは何をしますか? 数年前に私のことを気に入っているのであれば、(SDK_INT> = LOLLIPOP)if(SDK_INT> = LOLLIPOP)の場合、最初の(多くの)ブロックを作成することになります。

文字列

理想的には、プラットフォームAPI変更間のギャップを埋めるためにUtilsクラスとして機能するResourcesCompat、AppCompatResources、またはContextCompatについて知っておく必要があります。ただし、これらのクラスは、Android StudioのオートコンプリートgetDrawable()と同じくらい発見できません。

Kotlinの拡張機能は、既存のクラスに新しいメソッドを「追加」することで、従来のutilsクラスよりも優れた発見性と流暢なAPIを可能にします。 Android Studioはこれらのメソッドをオートコンプリートします。これらのメソッドは特定のバージョンのAndroidプラットフォームSDKに関連付けられていません。さらに、プラットフォームが進化するにつれて、それらの実装は変更される可能性があります。

これが、Googleが最近Android KTXを発表した理由です。ライブラリのセットは、Kotlin言語機能(拡張機能など)を利用することによってAndroid SDKをより直感的にすることを目指しています

そうは言っても、私はAndroid KTXの一部ではない私のお気に入りのAndroid拡張機能のいくつかを共有したいと思います。

pxToDp / dpToPx

DpとPxの間の相互運用を単純化します。

E.x. 2.pxToDp()4.dpToPx()

コード

@JvmOverloads @Dimension(unit = Dimension.PX) fun Number.dpToPx(
metrics: DisplayMetrics = Resources.getSystem().displayMetrics
): Float {
return toFloat() * metrics.density
}

@JvmOverloads @Dimension(unit = Dimension.DP) fun Number.pxToDp(
metrics: DisplayMetrics = Resources.getSystem().displayMetrics
): Float {
return toFloat() / metrics.density
}

getColorCompat / getDrawableCompat

上記の例に戻って、これらの拡張機能は発見可能性を最適化します。それらはAndroid Xのcompat関数のエイリアスとしてのみ機能します。

E.x. context.getColorCompat(R.color.green)context.getDrawableCompat(R.drawable.vector)

コード

@ColorInt fun Context.getColorCompat(@ColorRes colorRes: Int): Int {
return ContextCompat.getColor(this, colorRes)
}

fun Context.getDrawableCompat(@DrawableRes drawableRes: Int): Drawable {
return AppCompatResources.getDrawable(this, drawableRes)!!
}

色合い(tint)

tintは、Android Xに委任することによって、すべてのAPIレベルにわたってdrawableを着色するために使用できます。

E.x. getDrawableCompat(R.drawable.circle).tint(Color.Black)

コード

@CheckResult fun Drawable.tint(@ColorInt color: Int): Drawable {
val tintedDrawable = DrawableCompat.wrap(this).mutate()
DrawableCompat.setTint(tintedDrawable, color)
return tintedDrawable
}

@CheckResult fun Drawable.tint(context: Context, @ColorRes color: Int): Drawable {
return tint(context.getColorCompat(color))
}

inflate(膨らませる)

子ビューを親に追加せずにinflateさせるという一般的な操作を単純化します。

E.x. val view: CustomView = parent.inflate(R.layout.custom_view)

コード

@Suppress("UNCHECKED_CAST")
@JvmOverloads fun <V : View> ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): V {
return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot) as V
}

unsafeLazy

デフォルトでは、Kotlinの遅延機能は初期化コードが一度だけ実行されることを保証するためにスレッドセーフなロックを使用します。単一スレッドからのみアクセスされる変数(メインスレッドなど)の場合は、ロックを使用してパフォーマンスを向上させることを避けることができます。 unsafeLazyはこの実装のエイリアスです。

E.x. val green = unsafeLazy { getColorCompat(R.color.green) }

コード

fun <T> unsafeLazy(initializer: () -> T) = lazy(LazyThreadSafetyMode.NONE, initializer)

toActivity

コンテキストツリーをたどって、最も近いアクティビティを見つけます。

コード

fun Context.toActivity(): Activity? {
var context = this
while (context is ContextWrapper) {
if (context is Activity) {
return context
}
context = context.baseContext
}
return null
}

openWebPage

Chromeの[カスタム]タブを使用してウェブページを開くか、Chromeが利用できない場合は別のブラウザに切り替えます。注意:Gradleビルドファイルにandroidx.browser:ブラウザを追加する必要があります。

E.x. context.openWebPage(“www.instacart.com”)

コード

fun Context.openWebPage(url: String): Boolean {
// Format the URI properly.
val uri = url.toWebUri()

// Try using Chrome Custom Tabs.
try {
val intent = CustomTabsIntent.Builder()
.setToolbarColor(getColorCompat(R.color.primary))
.setShowTitle(true)
.build()
intent.launchUrl(this, uri)
return true
} catch (ignored: Exception) {}

// Fall back to launching a default web browser intent.
try {
val intent = Intent(Intent.ACTION_VIEW, uri)
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
return true
}
} catch (ignored: Exception) {}

// We were unable to show the web page.
return false
}

fun String.toWebUri(): Uri {
return (if (startsWith("http://") || startsWith("https://")) this else "https://$this").toUri()
}

これらの拡張機能をすべてプロジェクトに追加したい場合は、ここでまとめました。あなたの好きな拡張機能をコメントで教えてください!

これがおもしろい? 是非ご参加; Instacartが採用中です。どんな質問/コメント/フィードバックででもTwitter(@colinwhi)で私に手を差し伸べるか、単にこんにちはsayと言ってください。

この記事を編集してくれたJon Hsiehに感謝します。

タイトル:Using Kotlin Extensions to make the Android SDK friendlier

作者:Instacart

原文URL:https://tech.instacart.com/using-kotlin-extensions-to-make-the-android-sdk-friendlier-c355ec42d3cd

今すぐシェアしよう!
今すぐシェアしよう!