私は Android/Kotlin/Anko が初めてで、Anko 内から色 (およびおそらく他の) リソースにアクセスする方法について質問があります。
リソース文字列を設定するプロセスを簡素化するために をtextResource
渡すだけのようなヘルパーがあることは知っていますが、クラスのインスタンスを使用して色にアクセスするのはどうですか?R.string.my_color
Resources
View
Button
のサブクラスがあり、テキストの色を変更したいとしましょう。を使用するtextResource
と、色ではなくテキスト文字列が変更されます。使用する場合textColor
は、実際のリソース ID を使用して指定する必要があります。resources.getColor(R.color.my_color, null)
これは、オプションのテーマ パラメーターを渡す必要がなければそれほど面倒ではありません (null
こちら)。
ここで拡張機能を作成するとResources
便利ですか?
fun Int.fromResources(resources: Resources): Int {
return resources.getColor(this, null)
}
推奨される方法は何ですか?
編集
私はそれを行うように値の拡張機能を変更しました。これが本当にAndroidに適しtextColor
ているかどうかわからないことを除けば、これが最もクリーンな方法でした。
var android.widget.TextView.textColor: Int
get() = throw AnkoException("'android.widget.TextView.textColor' property does not have a getter")
set(v) = setTextColor(resources.getColor(v, null))