Skip to content

Instantly share code, notes, and snippets.

@c4software
Last active Mar 15, 2021
Embed
What would you like to do?
Un RecyclerView en 3 fichiers
class ExempleAdapter(private val deviceList: Array<Device>, private val onClick: ((selectedDevice: Device) -> Unit)? = null) : RecyclerView.Adapter<ExempleAdapter.ViewHolder>() {
// Comment s'affiche ma vue
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun showItem(device: Device, onClick: ((selectedDevice: Device) -> Unit)? = null) {
itemView.findViewById<TextView>(R.id.title).text = device.name
if(onClick != null) {
itemView.setOnClickListener {
onClick(device)
}
}
}
}
// Retourne une « vue » / « layout » pour chaque élément de la liste
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_device, parent, false)
return ViewHolder(view)
}
// Connect la vue ET la données
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.showItem(deviceList[position], onClick)
}
override fun getItemCount(): Int {
return deviceList.size
}
}
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"
android:text="@string/app_name"
android:textSize="16sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
rvDevices.layoutManager = LinearLayoutManager(this)
rvDevices.adapter = ExempleAdapter(emptyArray()) { item ->
Toast.makeText(this@UtilisationActivity, "Connexion à " + item.name, Toast.LENGTH_SHORT).show()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment