Home > Back-end >  How to make a list of images in a fragment in Kotlin?
How to make a list of images in a fragment in Kotlin?

Time:05-17

I'm new to Kotlin and Android development and I wanted to make a fragment that has a ListView of ImageViews but for some odd reason I get an error that says:

java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView

Here is my Fragment.kt code

var array = arrayOf(
        R.drawable.serbia,
        R.drawable.croatia,
        R.drawable.bulgaria,
        R.drawable.azerbejdzan,
        R.drawable.hungari)

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

        val context = context as MainActivity

        val lv = context.findViewById(R.id.listview_1) as ListView

        val adapter = ArrayAdapter(context, R.layout.simple_list_item_1, R.id.image1, array)
        lv.adapter = adapter
}

And here is my simple_list_item_1.xml

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@ id/image1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dip"
    tools:ignore="ContentDescription">
</ImageView>

I made this using a list of Strings and a TextView and it works good but I cannot seem to figure how to do it with Images. Any advice?

CodePudding user response:

You should create new CustomAdapter which is extended from BaseAdapter and this adapter should take the array , context as parameters in constructor . You should implement getView method of this adapter and use the layout inside this method. Find imageview from this layout using findViewById method and set image into this component . at the end of method return layout as result . if you have any question , you can ask .Please check this url : https://demonuts.com/android-listview-kotlin/

  • Related