How to display images in a ListView in Kotlin Android
How to display images in a ListView in Kotlin Android.
Here is a step-by-step tutorial on how to display images in a ListView in Kotlin Android:
First, make sure you have the necessary permissions in your AndroidManifest.xml file to access the internet. Add the following line inside the
<manifest>tag:<uses-permission android:name="android.permission.INTERNET" />Create a new Kotlin class for your custom adapter. This adapter will be responsible for populating the ListView with image items. Inside this class, add the following code:
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
class ImageAdapter(context: Context, private val imageUrls: List<String>) :
ArrayAdapter<String>(context, 0, imageUrls) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var itemView = convertView
if (itemView == null) {
itemView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false)
}
val imageView: ImageView = itemView!!.findViewById(R.id.imageView)
// Use a library like Picasso or Glide to load the image from the URL into the ImageView
// Example using Picasso:
Picasso.get().load(imageUrls[position]).into(imageView)
return itemView
}
}In this code, we extend the
ArrayAdapterclass and override thegetViewmethod. Inside this method, we inflate the layout for each item in the ListView and load the image from the URL into the ImageView using a library like Picasso or Glide.Create a new layout file for the ListView item (e.g.,
list_item.xml). Inside this layout file, add an ImageView to display the image:<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop" />Make sure to customize the layout according to your requirements.
In your activity or fragment, initialize the ListView and set the custom adapter to it:
import android.os.Bundle
import android.widget.ListView
class MainActivity : AppCompatActivity() {
private lateinit var listView: ListView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
listView = findViewById(R.id.listView)
val imageUrls = listOf(
"https://example.com/image1.jpg",
"https://example.com/image2.jpg",
"https://example.com/image3.jpg"
)
val adapter = ImageAdapter(this, imageUrls)
listView.adapter = adapter
}
}In this code, we initialize the ListView and set the custom adapter to it. Make sure to replace the
imageUrlslist with your own list of image URLs.Run your app and you should see the ListView populated with images fetched from the provided URLs.
That's it! You have successfully displayed images in a ListView in Kotlin Android.