---
# System prepended metadata

title: 2020-04-20 | Kotlin | Recycler view
tags: [android, kotlin, glide, gobelins, fragments]

---

# 2020-04-20 | Kotlin | Recycler view

###### tags: `kotlin` `android` `gobelins` `glide` `fragments`

Afficher une liste d'éléments dans une recycler view, avec des images en utilisant Glide et les fragments.

## Permissions (AndroidManifest.xml)
```xml
<uses-permission android:name="android.permission.INTERNET"/>
```

## Dependencies (build.graddle)
```
implementation 'androidx.recyclerview:recyclerview:1.2.0-alpha02'
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
```

> [color=#63b5dd]
> 
> Ne pas oublier de resynchroniser si nécessaire.


## Code

### MainActivity.kt
```kotlin
class MainActivity : AppCompatActivity() {

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

        // Créer nouvelle instance fragment
        change(CategoriesFragment())
    }
}

fun FragmentActivity.change(fragment: Fragment) {
    supportFragmentManager.beginTransaction().apply {
        replace(R.id.container, fragment)
        addToBackStack(null)
    }.commit()
}
```

### Categoriesfragment.kt
```kotlin
class Categoriesfragment: Fragment() {

    private lateinit var adapter: ArrayAdapter<String>
    private lateinit var recycler_view: RecyclerView

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.categories_view,container,false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recycler_view = view.findViewById(R.id.recycler_view)
        bindRecyclerView()

    }

    private fun bindRecyclerView() {
        val categories = listOf(
            Categorie("Politique", "C'est ça la politique", "https://cdn.1min30.com/wp-content/uploads/2018/12/shutterstock_1075959185-copie.jpg"),
            Categorie("Economie","c'est l'économie", "https://lobservateur.info/wp-content/uploads/2019/04/5b02e7a498cdc.jpg"),
            Categorie("Education","c'est l'éducation", "https://www.touteleurope.eu/fileadmin/_processed_/0/7/politique-euro-formation-education-a387ed0502.jpg"),
            Categorie("Pandémie","c'est la pandémie", "https://cdn.futura-sciences.com/buildsv6/images/wide1920/5/5/a/55adb6fe27_50161581_pandemie-denisismagilov-adobe-stock.jpg"),
            Categorie("Sciences","c'est la sciences", "https://cdn.futura-sciences.com/buildsv6/images/wide1920/a/0/2/a0269d7a2e_50155960_science-20e-siecle-artinspiring-fotolia.jpg"),
            Categorie("Ecologie","c'est l'écologie", "https://youmatter.world/app/uploads/sites/3/2018/08/ecologie-solutions.jpg")
        )
        val adapterRecycler = CategorieAdapter(categories)
        recycler_view.layoutManager = LinearLayoutManager(context)
        recycler_view.adapter = adapterRecycler
    }
}
```

> [color=#63b5dd]
> 
> Attention au format des images. Certains ne sont pas pris en compte...

### categories_view.xml
```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=".MainActivity"
    >

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="377dp"
        android:layout_height="483dp"
        app:layout_constraintBottom_toTopOf="@+id/btn_articles_fragment"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:listitem="@layout/list_item" />

    <Button
        android:id="@+id/btn_articles_fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Articles fragment"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />


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

### Categorie.kt
```kotlin
class Categorie(name: String, description: String, url:String) {
    val name:String = name
    val description:String = description
    val url:String = url
}
```

### CategorieAdapter.kt
```kotlin
@GlideModule

class CategorieAdapter(private val dataset: List<Categorie>) :
    RecyclerView.Adapter<CategorieAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val rootView = LayoutInflater.from(parent.context)
            .inflate(R.layout.list_item, parent, false)
        return ViewHolder(rootView)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) =
        holder.bind(dataset[position])

    override fun getItemCount(): Int = dataset.size

    class ViewHolder(val root: View) : RecyclerView.ViewHolder(root) {

        fun bind(item: Categorie) {
            val txtTitle = root.findViewById<TextView>(R.id.categorie_name)
            val txtDesc = root.findViewById<TextView>(R.id.categorie_description)
            val img = root.findViewById<ImageView>(R.id.categorie_image)
            Glide.with(root.context).load(item.url).fitCenter().into(img)
            txtTitle.text = item.name
            txtDesc.text = item.description
        }
    }
}
```

### list_item.xml
```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="wrap_content">

    <TextView
        android:id="@+id/categorie_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textStyle="bold"
        android:textSize="26sp"
        android:textAlignment="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        tools:ignore="MissingConstraints" />

    <ImageView
        android:id="@+id/categorie_image"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/categorie_name"
        app:srcCompat="@drawable/ic_launcher_background" />

    <TextView
        android:id="@+id/categorie_description"
        android:layout_width="0dp"
        android:layout_height="60dp"
        android:text="TextView"
        android:textAlignment="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/categorie_image" />

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