LoginSignup
2
2

More than 5 years have passed since last update.

RecyclerView.ViewHolderでKotlin Android Extensionsを利用する

Posted at

基本的には findViewById と同じ

以下のようなレイアウトファイルを使った場合、
ViewHolderの itemView に生えている対象のビューを捕まえてあげるだけです。

view_text.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
holder.itemView.apply {
    textView.text = context.getString(R.string.app_name)
}

findViewById を使った場合は以下のようになるので、
同じことをやっていると考えればとくに難しいことはないでしょう。

holder.itemView.apply {
    findViewById<TextView>(R.id.textView).text = context.getString(R.string.app_name)
}

そのため、レイアウトファイルをincludeしたものも同じように扱えばよいです。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2