a-1-2.Viewの再利用機構(RecyclerView)

### a-1-2.Viewの再利用機構(RecyclerView)

#### 目標設定
[一覧に戻る](https://qiita.com/ryouta33/items/57f5e51a26086151a0da)

#### 課題
3. Activityから再利用するViewの値を設定できるか。
3. 再利用するViewのイベントをActivityで受け取れるか。

#### Github

https://github.com/wakizaka24/AndroidTest

#### テスト実装

```kotlin:RecyclerViewTestActivity.kt
class RecyclerViewTestActivity : AppCompatActivity(), TestRecyclerViewHolder.ItemClickListener {
    private lateinit var recyclerView: RecyclerView
    private lateinit var viewAdapter: RecyclerView.Adapter<*>
    private lateinit var viewManager: RecyclerView.LayoutManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_recycler_view_test)

        // 1. Activityから再利用するViewの値を設定できるか。
        // ・初期値の設定は可能でした。

        val strings = listOf("水素", "窒素", "炭素", "酸素", "リン",
            "硫黄", "マグネシウム", "カルシウム", "ナトリウム", "カリウム",
            "ストロンチウム", "バリウム", "鉄", "亜鉛", "銅", "鉛", "銀",
            "金", "白金", "水銀")

        viewAdapter = TestRecyclerAdapter(this, this, strings)
        viewManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)

        recyclerView = findViewById<RecyclerView>(R.id.testRecyclerView).apply {
            // サイズ変更を行わない
            setHasFixedSize(true)
            layoutManager = viewManager
            adapter = viewAdapter
        }
    }

    // 2. 再利用するViewのイベントをActivityで受け取れるか。
    // ・セルの選択はイベントの取得が可能でした。

    override fun onItemClick(view: View, position: Int) {
        Toast.makeText(applicationContext, "tapped position = $position",
            Toast.LENGTH_SHORT).show()
    }
}
```

```xml:activity_recycler_view_test.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".RecyclerViewTestActivity"
    >

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/testRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:paddingTop="23dp"
        android:paddingBottom="23dp"
        android:clipToPadding="false"
        />

</androidx.constraintlayout.widget.ConstraintLayout>
```

```kotlin:TestRecyclerAdapter.kt
class TestRecyclerAdapter(private val context: Context,
                          private val itemClickListener: TestRecyclerViewHolder.ItemClickListener,
                          private val itemList:List<String>) : RecyclerView.Adapter<TestRecyclerViewHolder>() {

    private var mRecyclerView : RecyclerView? = null

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        mRecyclerView = recyclerView
    }

    override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
        super.onDetachedFromRecyclerView(recyclerView)
        mRecyclerView = null
    }

    override fun onBindViewHolder(holder: TestRecyclerViewHolder, position: Int) {
        holder.let {
            it.itemTextView1.text = itemList.get(position)
        }
    }

    override fun getItemCount(): Int {
        return itemList.size
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TestRecyclerViewHolder {
        val layoutInflater = LayoutInflater.from(context)
        val mView = layoutInflater.inflate(R.layout.recycler_view_item_test, parent, false)

        mView.setOnClickListener { view ->
            mRecyclerView?.let {
                itemClickListener.onItemClick(view, it.getChildAdapterPosition(view))
            }
        }

        return TestRecyclerViewHolder(mView)
    }
}
```

```kotlin:TestRecyclerViewHolder.kt
class TestRecyclerViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    interface ItemClickListener {
        fun onItemClick(view: View, position: Int)
    }

    val itemView1: View = view.findViewById(R.id.itemView1)
    val itemTextView1: TextView = view.findViewById(R.id.itemTextView1)

    init {
    }
}
```

```xml:recycler_view_item_test.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="23dp"
    android:layout_marginTop="6dp"
    android:layout_marginEnd="23dp"
    android:layout_marginBottom="6dp"
    card_view:cardElevation="2dp"
    android:foreground="?android:attr/selectableItemBackground"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:gravity="center_vertical"
        tools:ignore="UseCompoundDrawables">

        <View
            android:id="@+id/itemView1"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_margin="8dp"
            android:background="@color/purple_500"
            />

        <TextView
            android:id="@+id/itemTextView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />

    </LinearLayout>

</androidx.cardview.widget.CardView>
```

<img src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1545849/f2a3801b-28ec-f1bf-2a98-eb0ec1bd0497.png
" width="300" />