Categories: Android

Kotlin Android ExtensionsをViewHolderで使う

viewholderでもKotlin Android Extensionsを使う方法のご紹介

ぐぐったらこんなことがかいてあった

I am new in kotlin. I have found and tried to use synthetic method instead of annoying method findViewById in my Activity class, but I have found "If we want to call the synthetic properties on View (
Kotlin synthetic in Adapter or ViewHolder - Stack Overflow

Simple example from https://github.com/antoniolg/Kotlin-for-Android-Developers

import kotlinx.android.synthetic.item_forecast.view.*

class ForecastListAdapter() : RecyclerView.Adapter() {

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {

        fun bindForecast(forecast: Forecast) {
            itemView.date.text = forecast.date.toDateString()
        }
    }
}

気をつけるべき点はactivityやfragmentと違ってimport先にviewがついてる点。

import kotlinx.android.synthetic.main.item_forecast.view.*

※現在はKotlin Android ExtensionsにてUnresolved referenceと言われてしまう対策法でも紹介したとおり、mainをつけるのを忘れない

itemViewはViewHolderに定義されており、そのままそのプロパティとしてlayoutで定義した値が使えるようになっている。

itemViewが自分で定義しているものと勘違いして気づくのに時間がかかってしまった・・・

まとめ

ViewHolderやadapterでもKotlin Android Extensionsは使える!!!!!!!

mogmet

Share
Published by
mogmet