AnkoはAndroid開発を楽にするKotlinライブラリです。
KotlinでAndroid開発! ライブラリAnkoでのUI構築を試すの回ではAnkoのメイン機能である、DSLでのUI構築を試しました。
今回はそれ以外のAnkoの機能を試してみようと思います。
Intent
別Activityを起動したり別アプリケーションを呼んだりと、AndroidにおいてIntentは重要な意味を持ちます。
KotlinでオーソドックスにIntentを使うのであれば次のようになりますね。
FooActivityに遷移します。
1 2 3 | val intent = Intent() intent.putExtra( "name" , "Alice" ) startActivity(intent) |
同様のことがAnkoを使うと一行で記述でできます。
1 | startActivity<FooActivity>( "name" to "Alice" ) |
Toast
Toast表示を簡潔に書けます。
1 2 | toast( "toast表示" ) longToast( "長いToast表示" ) |
ありがちなshow()の呼び忘れも気にしなくよくなります。
Dialog
DialogをDSLを使って表示することができます。
AlertDialog
1 2 3 4 | alert( "更新してよろしいですか" , "確認" ) { positiveButton( "OK" ) { /* クリックイベント処理 */ } negativeButton( "キャンセル" ) {} }.show() |
CustomViewDialog
カスタムレイアウトを持つDialogもDSLを使って記述できます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | alert { customView { verticalLayout { val email = editText { hint = "email" }.lparams{ width = matchParent topMargin = dip( 16 ) leftMargin = dip( 4 ) rightMargin = dip( 4 ) bottomMargin = dip( 4 ) } val password = editText { hint = "password" }.lparams{ width = matchParent topMargin = dip( 4 ) leftMargin = dip( 4 ) rightMargin = dip( 4 ) bottomMargin = dip( 16 ) } positiveButton( "登録" ) {} negativeButton( "キャンセル" ) } } }.show() |
Log出力
Android開発ではLogクラスによるデバッグは欠かせません。
1 2 3 4 5 6 | class MainActivity : AppCompatActivity(), AnkoLogger { fun hogeMethod() { //Log.d("tag", 5.toString()) debug( 5 ) } } |
AnkoLoggerインタフェースを実装することで、Log.dであればdebugと記述できます。タグ指定は必要なく、またString以外の値を引数に取れます。各Log出力とAnkoLoggerメソッドの対応は以下の通りです。
android.util.Log | AnkoLogger |
---|---|
v() |
verbose() |
d() |
debug() |
i() |
info() |
w() |
warn() |
e() |
error() |
wtf() |
wtf() |
非同期処理
非同期処理とUIスレッドが協調するような処理を書きたいとき、Ankoを使うと次のように記述できます。
1 2 3 4 5 6 7 8 9 10 11 12 13 | class MainActivity : AppCompatActivity() { ... fun doAsyncAction() { doAsync { //バックグラウンド処理 uiThread { //コールバック処理 toast( "Done" ) } } } } |
doAsyncブロックに時間がかかる処理を呼び出し、uiThreadで受けることでUIに絡む非同期処理を簡潔に書けます。
Handlerを使って書くより直感的ですね。
おわりに
Ankoライブラリの様々な機能を紹介しました。巣のAndroidでは冗長になりがちなところを楽にできるので使いこなすと便利そうです。