头图

This article is the third in a series of articles that introduces the introduction of RecyclerView If you already have a certain understanding of creating RecyclerView, please continue reading this article. If you are not already familiar with it, I suggest you read first article this series.

When using RecyclerView display list data, you may need to respond to click events of list elements. The response processing includes: opening a page containing more data, displaying a toast, deleting an element, and so on. Although the related response events are countless, they all need to be implemented onClick()

defines the click action

Before creating the listener, add a function to the Activity class to handle the response operation after the click.

<!-- Copyright 2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

private fun adapterOnClick(flower: Flower) {
   val intent = Intent(this, FlowerDetailActivity()::class.java)
   intent.putExtra(FLOWER_ID, flower.id)
   this.startActivity(intent)
}

Next, modify the constructor of the Adapter to pass in the onClick() function.

<!-- Copyright 2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

class FlowersAdapter(private val onClick: (Flower) -> Unit) :
  ListAdapter<Flower, RecyclerView.ViewHolder>(FlowerDiffCallback())

In the Activity class, pass in the click event function just created when initializing the Adapter.

<!-- Copyright 2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

val flowersAdapter = FlowersAdapter { flower ->
  adapterOnClick(flower)
}

add onClickHandler()

Now that the response processing has been defined, it can be associated with the ViewHolder of the Adapter.

Modify ViewHolder and pass in onClick() as a parameter.

<!-- Copyright 2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

class FlowerViewHolder(itemView: View, val onClick: (Flower) -> Unit) :
  RecyclerView.ViewHolder(itemView)

In the initialization code, call itemView's setOnClickListener{}.

 <!-- Copyright 2019 Google LLC. 
    SPDX-License-Identifier: Apache-2.0 -->
 
 init {
    itemView.setOnClickListener {
      currentFlower?.let {
          onClick(it)
       }
    }
}

Get it done! Now your RecyclerView can respond to click events.

Happy programming!

Next

complete example that includes onClick().

Thank you for reading the third article of RecyclerView series Please continue to pay attention to more about RecyclerView in the future.

If you want to know more about onClick(), please refer to official document .


Android开发者
404 声望2k 粉丝

Android 最新开发技术更新,包括 Kotlin、Android Studio、Jetpack 和 Android 最新系统技术特性分享。更多内容,请关注 官方 Android 开发者文档。