ググってでてきた方法でうまくいかなかったのでメモ。
Kotlinのバージョンは1.1.2
うまくいかなかった箇所
KotlinでBindingAdapter使う場合は、Extension使えばいい(参考リンク)とあるが、Extensionだとうまくいかず。。。
http://stackoverflow.com/questions/40085724/kotlin-custom-attribute-databinding を参考にトップレベルに定義したらうまくいった。
ただ、なぜExtensionだとうまくいかないのかはわからず。ログにはこのようにでていた。java.lang.NoSuchMethodException: com.android.ide.common.blame.Message.<init>
うまくいったコード
card_view.xml
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="cardData"
type="com.hoge.model.entity.CardData" />
</data>
...
<ImageView
android:id="@+id/card_view_user_icon"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginEnd="8dp"
app:imageURL="@{cardData.userImageURL}" />
</layout>
ImageViewBinder.kt
@BindingAdapter("app:imageURL")
// なぜかImageView.loadImageだとビルドとおらない・・
fun loadImage(imageView: ImageView, url: String) {
Picasso.with(imageView.context).load(url).into(imageView)
}
Tips
- ログの場所は Android Studio の Help > Show Log in Finder
-
app:imageURL
のapp
を使ってる理由は 人跡既踏: 名前空間「http://schemas.android.com/apk/res-auto」の出自と意味 にあるとおり。カスタムの属性はapp
を使う。ビルド時にアプリのURIに置き換わるらしい。