How to add headers and footers to a ListView in Kotlin Android
How to add headers and footers to a ListView in Kotlin Android.
Here's a step-by-step tutorial on how to add headers and footers to a ListView in Kotlin Android:
Step 1: Create a new Android project
Create a new Android project in Android Studio. Choose an appropriate project name, package name, and select Kotlin as the programming language.
Step 2: Add dependencies
Open the build.gradle file of your app module and add the following dependencies:
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'androidx.recyclerview:recyclerview:1.2.1'
Step 3: Design the layout
In the activity_main.xml layout file, add a ListView with an ID:
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Step 4: Create layout files for header and footer
Create two layout files named header_layout.xml and footer_layout.xml in the res/layout directory. Design these layouts as per your requirements.
Step 5: Create a custom adapter
Create a new Kotlin class named CustomAdapter and extend it from BaseAdapter. Override the necessary methods:
class CustomAdapter(private val context: Context, private val dataList: List<String>) : BaseAdapter() {
override fun getCount(): Int {
return dataList.size
}
override fun getItem(position: Int): Any {
return dataList[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var view = convertView
if (view == null) {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
view = inflater.inflate(android.R.layout.simple_list_item_1, null)
}
val textView = view?.findViewById(android.R.id.text1) as TextView
textView.text = dataList[position]
return view
}
}
Step 6: Implement headers and footers in the ListView
In your MainActivity.kt file, add the following code:
val listView = findViewById<ListView>(R.id.listView)
// Inflate and add the header view
val headerView = LayoutInflater.from(this).inflate(R.layout.header_layout, listView, false)
listView.addHeaderView(headerView)
// Inflate and add the footer view
val footerView = LayoutInflater.from(this).inflate(R.layout.footer_layout, listView, false)
listView.addFooterView(footerView)
// Create the data list
val dataList = listOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5")
// Create and set the adapter
val adapter = CustomAdapter(this, dataList)
listView.adapter = adapter
That's it! You have successfully added headers and footers to your ListView using a custom adapter in Kotlin Android.