Blog_Post
Utiliser ExpandableListView sur Android avec Kotlin
cat ~/blog/utiliser_expandablelistview_sur_android_avec_kotlin.md
Last updated:
Présentation de ExpandableListView
ExpandableListView est un widget Android qui permet de regrouper les données d’une liste en catégories, chacune pouvant être développée pour afficher ou réduite pour masquer ses éléments enfants. C’est particulièrement utile pour afficher des listes complexes avec plusieurs niveaux de données.
Mise en place du projet
Pour commencer, vous devez configurer un projet Android dans Android Studio. Suivez ces étapes :
- Ouvrez Android Studio et créez un nouveau projet.
- Sélectionnez « Empty Activity » et cliquez sur « Next ».
- Nommez votre projet et définissez le langage sur « Kotlin ».
- Cliquez sur « Finish » pour créer le projet.
Création de la mise en page
Ensuite, vous devrez créer la mise en page pour votre ExpandableListView. Ouvrez le fichier activity_main.xml et
ajoutez le code XML suivant :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ExpandableListView
android:id="@+id/expandable_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Cette mise en page inclut simplement un ExpandableListView qui occupe tout l’écran.
Configuration des données
Pour alimenter le ExpandableListView, vous devez définir les données. En général, ces données sont structurées sous
forme de HashMap où chaque clé représente un groupe et chaque valeur est une liste d’enfants pour ce groupe.
Créez un nouveau fichier appelé DataProvider.kt et ajoutez le code suivant :
object DataProvider {
fun getData(): HashMap<String, List<String>> {
val expandableListDetail = HashMap<String, List<String>>()
val group1 = listOf("Enfant 1", "Enfant 2")
val group2 = listOf("Enfant 3", "Enfant 4")
expandableListDetail["Groupe 1"] = group1
expandableListDetail["Groupe 2"] = group2
return expandableListDetail
}
}
Création de l’adaptateur
Ensuite, créez un adaptateur personnalisé pour faire le lien entre les données et le ExpandableListView. Créez un
nouveau fichier appelé CustomExpandableListAdapter.kt et ajoutez le code suivant :
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseExpandableListAdapter
import android.widget.TextView
class CustomExpandableListAdapter(
private val context: Context,
private val expandableListTitle: List<String>,
private val expandableListDetail: HashMap<String, List<String>>
) : BaseExpandableListAdapter() {
override fun getChild(listPosition: Int, expandedListPosition: Int): Any {
return this.expandableListDetail[this.expandableListTitle[listPosition]]!![expandedListPosition]
}
override fun getChildId(listPosition: Int, expandedListPosition: Int): Long {
return expandedListPosition.toLong()
}
override fun getChildView(listPosition: Int, expandedListPosition: Int, isLastChild: Boolean,
convertView: View?, parent: ViewGroup): View {
var convertView = convertView
val expandedListText = getChild(listPosition, expandedListPosition) as String
if (convertView == null) {
val layoutInflater = this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
convertView = layoutInflater.inflate(android.R.layout.simple_list_item_1, null)
}
val expandedListTextView = convertView!!.findViewById<TextView>(android.R.id.text1)
expandedListTextView.text = expandedListText
return convertView
}
override fun getChildrenCount(listPosition: Int): Int {
return this.expandableListDetail[this.expandableListTitle[listPosition]]!!.size
}
override fun getGroup(listPosition: Int): Any {
return this.expandableListTitle[listPosition]
}
override fun getGroupCount(): Int {
return this.expandableListTitle.size
}
override fun getGroupId(listPosition: Int): Long {
return listPosition.toLong()
}
override fun getGroupView(listPosition: Int, isExpanded: Boolean, convertView: View?,
parent: ViewGroup): View {
var convertView = convertView
val listTitle = getGroup(listPosition) as String
if (convertView == null) {
val layoutInflater = this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
convertView = layoutInflater.inflate(android.R.layout.simple_expandable_list_item_1, null)
}
val listTitleTextView = convertView!!.findViewById<TextView>(android.R.id.text1)
listTitleTextView.text = listTitle
return convertView
}
override fun hasStableIds(): Boolean {
return false
}
override fun isChildSelectable(listPosition: Int, expandedListPosition: Int): Boolean {
return true
}
}
Implémentation de ExpandableListView
Maintenant, assemblons le tout dans la MainActivity. Ouvrez MainActivity.kt et ajoutez le code suivant :
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private lateinit var expandableListAdapter: CustomExpandableListAdapter
private lateinit var expandableListTitle: List<String>
private lateinit var expandableListDetail: HashMap<String, List<String>>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
expandableListDetail = DataProvider.getData()
expandableListTitle = ArrayList(expandableListDetail.keys)
expandableListAdapter = CustomExpandableListAdapter(this, expandableListTitle, expandableListDetail)
expandableListView.setAdapter(expandableListAdapter)
}
}
Ce code initialise le ExpandableListView, définit l’adaptateur et le remplit avec les données.
Gestion des événements de clic
Pour gérer les événements de clic sur les éléments de groupe et les éléments enfants, ajoutez le code suivant à MainActivity :
expandableListView.setOnGroupExpandListener { groupPosition ->
// Gérer l'événement d'expansion du groupe
}
expandableListView.setOnGroupCollapseListener { groupPosition ->
// Gérer l'événement de réduction du groupe
}
expandableListView.setOnChildClickListener { parent, v, groupPosition, childPosition, id ->
// Gérer l'événement de clic sur un enfant
false
}
Conclusion
ExpandableListView est un widget puissant sur Android qui vous permet d’afficher des données dans un format hiérarchique.
En suivant ce guide, vous devriez être en mesure d’implémenter un ExpandableListView dans votre application Android,
de le personnaliser avec vos propres données et de gérer divers événements pour créer une expérience utilisateur dynamique.